Simple Factory mode, because the method to create the object is static, so it is also called the Quiescent Factory mode.
Origin: Static Factory mode is to have a unified creation method for the product class, and for the client how to create "product" is not need to know and do not need to tube.
New "Products" from the information provided by the client
Key code:
Class Factory () {
public static farther () {
if ("Sub1") {
return new Sub1 ();
}else if ("Sub2") {
return new SUB2 ();
}
}
}
Class farther () {}
Class Sub1 extends Farther () {}
Class Sub2 extends Farther () {}
Second, the factory model, because the simple Factory mode does not conform to the opening and shutting principle, so the factory model needs to solve this problem.
Key points: Need a factory interface and a product base class, in the case of newly added products, new factories and products can be, in line with the open and closed principle.
The production of each product requires a factory. The advantage is that it conforms to the open/close principle (closed to modification, opening to extension). The disadvantage is that it causes too many classes (each product requires a product subclass and a factory class)
Interface Factory () {
Public Product FactoryMethod ();
}
Class FactoryType1 implements Factory () {
Public Product FactoryMethod () {
return new ProductSub1 ();
}
}
Class Product () {}
Class ProductSub1 extends Farther () {}
Third, the abstract Factory mode, the product too much Factory mode, the number of classes will be greatly increased, the abstract factory model can be the product of sub-family implementation to create objects.
The addition of product families is in line with the principle of open and closed, the change of product structure is non-closed principle.
Abstract interface Abstractfactory () {//each sub-factory must be given the production of A, B, two products of this factory. Each factory can have its own implementation (that is, different brands of products)
Public abstract producta productafactory ();
Public abstract PRODUCTB productafactory ();
}
Understanding the Factory model