The main point of software design is high cohesion and low coupling, and the Factory mode satisfies this requirement, first the code
Create a new interface:
Package Factory;public Interface Interface {public void operate ();
Build a second implementation class:
Package Factory;public class Impl implements interface{@Overridepublic void operate () {SYSTEM.OUT.PRINTLN ("Implementing interface Method");}}
Factory Method:
Package Factory;public class Factory {private Interface in;public Interface getinterface () {if (in = = null) {//If not present, create instance I n = new Impl ();} return in;}}
Under test:
Package factory;/** Factory mode * @author Mercy * */public class Test {public static void main (string[] args) {Factory f=new facto Ry ();//Create Factory Instance Interface In=f.getinterface ();//Get Impl Instance in.operate () through factory method;}}
Results:
Implementing interface Methods
This is the advantage of the factory model is to achieve interface programming, and there is no significant advantage, and if you create a few more interfaces of the implementation class, if you follow the normal method, you need to create more instances of several objects
Package Factory;public class Badtest{public static void Main (string[] args) {Interface i=new Impl (); I.operate ();}}
The same result can be achieved with the above method, however, if you add several implementation classes, you will have more new object instances. In this way, the coupling between the interface and the implementation class is too high, and too many instances are not conducive to management, but if the unified
These instances are processed in the factory, the client only need to create a factory instance, call the appropriate factory method to get the object instance, and then get the corresponding object method, so that the client new multiple object instances, the client will create object procedure screen, the new class only need to modify the corresponding factory method class.
Java design mode----Factory mode