Factory method pattern of Java Design Pattern
I. definition is to define a factory interface for creating product objects, so that the subclass decides which instance object to instantiate, that is, to postpone the work of actually creating instance objects to the subclass, the core factory is no longer responsible for the creation of specific products. II. Implementation 1. Define Products
Package COM. product;/*** define abstract product class * @ author administrator **/public abstract class abstractproduct {private string name; Public abstractproduct () {} Public String getname () {return name;} public void setname (string name) {This. name = Name ;}}
Package COM. product;/*** product A * @ author administrator **/public class producta extends abstractproduct {public producta () {This. setname ("producta ");}}
Package COM. product;/*** product B * @ author administrator **/public class productb extends abstractproduct {public productb () {This. setname ("productb ");}}
2. Create a factory
Package com. Factory; import com. Product. abstractproduct;/*** defines the factory interface * @ author administrator **/public interface iproductfactory {public abstractproduct createproduct ();}
Package COM. factory; import COM. product. abstractproduct; import COM. product. producta;/*** factory implementation class * @ author administrator **/public class productfactory implements iproductfactory {@ overridepublic abstractproduct createproduct () {return New producta ();}}
3. Test
Package COM. main; import COM. factory. iproductfactory; import COM. factory. productfactory;/*** test class ** @ author administrator **/public class mainapp {public static void main (string [] ARGs) {iproductfactory pF = new productfactory (); system. out. print (PF. createproduct (). getname ());}}
Result output producta
If product B is to be produced at this time, we can create another factory entity class. As long as iproductfactory is implemented, the productb object is created in createproduct.
Iii. Design Principles
The principle of "open-close" is embodied, and the dependency inversion principle for modification and closure and wide expansion is embodied. Factories and products depend on abstraction, rather than specific implementation classes.
Iv. Applicable scenarios
A. when there may be many subtypes and different subclass implementations need to be added in the future, B. When a system is still in the framework design stage, I do not know which classes need to be instantiated in the future. C. The concept of a specific object is not required at the beginning of the system design (or the concept of a specific object is absent)