Java Design Pattern serialization (2) -- abstract factory pattern
Intent:
Provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
Applicability:
- A system must be independent of the creation, combination, and representation of its products.
- A system must be configured by one of multiple product generations.
- When you want to emphasize the design of a series of related product objects for joint use.
- When you provide a product class library, instead of displaying their interfaces.
Instance:
1. abstract computer device factory Interface
package Abstract_Factory_Pattern;public interface ComputerFactory {public CPU createCpu();public Displayer createDisplayer(); }
2. Implement the specific production of new and old device factories through the above Interfaces
package Abstract_Factory_Pattern;public class NewComputerFactory implements ComputerFactory{@Overridepublic CPU createCpu() {return new NewCup();}@Overridepublic Displayer createDisplayer() {return new NewDisplayer();}}
package Abstract_Factory_Pattern;public class OldComputerFactory implements ComputerFactory{@Overridepublic CPU createCpu() { return new OldCpu();}@Overridepublic Displayer createDisplayer() { return new OldDisplayer();} }
3. Define a CPU interface and a display interface
package Abstract_Factory_Pattern;public interface CPU { public void price();}
Package restart act_factory_pattern; public interface displayer {// display interface public void price ();}
4. Implement the above two interfaces
Package implements act_factory_pattern; public class newcup implements CPU {@ overridepublic void price () {system. Out. println ("New CPU expensive ");}}
Package implements act_factory_pattern; public class oldcpu implements CPU {@ overridepublic void price () {system. Out. println ("Old CPU is cheap ");}}
Package into act_factory_pattern; public class newdisplayer implements displayer {@ overridepublic void price () {system. Out. println ("the new monitor is expensive! ");}}
Package into act_factory_pattern; public class olddisplayer implements displayer {@ overridepublic void price () {system. Out. println ("Old display cheap ");}}
5. Test this mode.
Package implements act_factory_pattern; public class client {public static void main (string [] ARGs) {computerfactory = new newcomputerfactory (); computerfactory. createcpu (). price (); // The factory produces expensive computerfactory during the new computer period. createdisplayer (). price (); computerfactory = new oldcomputerfactory (); computerfactory. createcpu (). price (); // The factory produced a cheap computerfactory during the old-fashioned computer period. createdisplayer (). price ();}}
6. Thank you for browsing. Thank you for choosing axe.