
工厂方法模式解决了创建对象的需要,而无需指定将创建的对象的确切类。当您有超类的多个子类并希望根据某些条件或参数将对象创建委托给特定子类时,这非常有用。
工厂方法模式提供了一个用于在超类中创建对象的接口,但允许子类更改将创建的对象的类型。这通过确保客户端代码与工厂接口而不是直接与具体类交互来促进松散耦合。
工厂方法模式的一个实际示例是用于创建文档的框架。根据文档的类型(例如 pdf、html),相应的文档工厂会创建具有适当格式和功能的文档对象。
代码中的工厂方法模式
java
// Product interface
public interface Document {
void open();
void close();
}
// Concrete Product 1
public class PDFDocument implements Document {
@Override
public void open() {
System.out.println("Opening PDF document");
}
@Override
public void close() {
System.out.println("Closing PDF document");
}
}
// Concrete Product 2
public class HTMLDocument implements Document {
@Override
public void open() {
System.out.println("Opening HTML document");
}
@Override
public void close() {
System.out.println("Closing HTML document");
}
}
// Creator interface
public interface DocumentFactory {
Document createDocument();
}
// Concrete Creator 1
public class PDFDocumentFactory implements DocumentFactory {
@Override
public Document createDocument() {
return new PDFDocument();
}
}
// Concrete Creator 2
public class HTMLDocumentFactory implements DocumentFactory {
@Override
public Document createDocument() {
return new HTMLDocument();
}
}
// Client code
public class Client {
public static void main(String[] args) {
DocumentFactory factory1 = new PDFDocumentFactory();
Document pdfDocument = factory1.createDocument();
pdfDocument.open();
pdfDocument.close();
DocumentFactory factory2 = new HTMLDocumentFactory();
Document htmlDocument = factory2.createDocument();
htmlDocument.open();
htmlDocument.close();
}
}
以上就是了解工厂方法设计模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号