The problem with factory method mode is that class creation relies on the factory class, that is, if you want to expand the program, the factory class must be modified, which violates the closure principle, so from the design point of view, there are certain problems, how to solve? Use the abstract factory pattern to create multiple factory classes so that once you need to add new functionality, you can add new factory classes directly, without having to modify the previous code. Because the abstract factory is not very well understood, we first look at the diagram, and then the code, it is more easily understood.
1 PackageCom.qcf.test2;2 /**3 * Abstract Factory mode4 * Create an interface for the method5 * Create an interface for the factory class6 * If you add another car, then create a method class that inherits car and creates a factory inheritance factory7 * @authorComputer8 *9 */Ten Public classAbstractfactory { One Public Static voidMain (string[] args) { ACar car=Newbigcarfactory (). product (); - car.getname (); - } the } - /** - * Factory class interface - * @authorComputer + * - */ + Interfacefactory{ A Car product (); at } - /** - * BMW factory Production class - * @authorComputer - * - */ in classBmwcarfactoryImplementsfactory{ - to @Override + PublicCar Product () { - return NewBMW (); the } * } $ Panax Notoginseng /** - * Big factory Production class the * @authorComputer + * A */ the classBigcarfactoryImplementsfactory{ + - @Override $ PublicCar Product () { $ return NewBigcar (); - } - } the - /**Wuyi * Interface the * @authorComputer - * Wu */ - Interfacecar{ About voidGetName (); $ } - /** - * Subclass that implements the interface - * @authorComputer A * + */ the classBmwImplementscar{ - @Override $ Public voidGetName () { theSystem.out.println ("BMW Car ....")); the } the } the /** - * Subclass that implements the interface in * @authorComputer the * the */ About classBigcarImplementscar{ the @Override the Public voidGetName () { theSystem.out.println ("Big Car ..."); + } -}
View Code
Two abstract factory modes of Java design mode (abstract Factory)