A little discussion about the factory approach, we know that the factory method belongs to the type creation pattern, and the abstract factory belongs to the object creation pattern, and the so-called class creation pattern is to defer the creation work to the subclass, while the object creation pattern is deferred to another object.
And the design pattern indicates that the class pattern handles the relationships between classes and subclasses, which are established by inheritance, static, and determined at compile time. Object mode deals with the relationships between objects, is dynamic, and the runtime can be changed and dynamic.
A factory method is a type-creation pattern, so its creation is done by subclasses, rather than by using objects, and there is an example in the motivation section of the factory method in design mode, whose classes are roughly as follows:
//抽象产品,可以是接口或者抽象类
public abstract class document {
public void open(){
...............
...............
}
public void close(){
...............
...............
}
public void save();
}
//具体的产品,
public class Mydocument extends document{
public void open(){
.............
..............
}
...............
}
我们工厂方法
public abstract class appliaction {
//该方法是工厂方法,由子类实现
public abstract document createDocument();
//模板方法,在方法中使用了工厂方法
pubic void newDocument(){
//使用工厂方法,获得doc,而实际有子类完成,//这里可以看出,对象的创建,是通过继承来实现,是静态的,编译时已经确定//而不是通过对象的委托来实现,故属于类创建型模式
Document doc=createDocument();
doc.open();
....................
doc.save();
}
}
The specific factory implements a subclass to implement the factory method:
public class myappliaction extends appliaction {
public document createDocument(){
return new Mydocument();
}
}