Most from: http://blog.csdn.net/zhengzhb/article/details/7359385
The factory method mode simply abstracts the parts of the objects created in the factory into virtual classes. In this way, we can reduce the logic in the factory class method.
The biggest advantage of the simple factory mode is that the factory class contains the necessary logic judgment, and the related class is dynamically instantiated according to the selection conditions of the client. Note that the related class is not just a class.
Typical applications
To illustrate the advantages of the factory model, there may be no more suitable example than assembling a car. The scenario is as follows: a car consists of an engine, a wheel, and a chassis. Now a car needs to be assembled and handed over to the caller. If the factory mode is not used, the Code is as follows:
Class engine {public void getstyle () {system. out. println ("this is the car's engine") ;}} class underpan {public void getstyle () {system. out. println ("this is the car chassis") ;}} Class Wheel {public void getstyle () {system. out. println ("this is a car tire") ;}} public class client {public static void main (string [] ARGs) {engine = new engine (); underpan = new underpan (); wheel = new wheel (); ICAR car = new car (underpan, wheel, engine); car. show ();}}
Factory method
interface IFactory {public ICar createCar();}class Factory implements IFactory {public ICar createCar() {Engine engine = new Engine();Underpan underpan = new Underpan();Wheel wheel = new Wheel();ICar car = new Car(underpan, wheel, engine);return car;}}public class Client {public static void main(String[] args) {IFactory factory = new Factory();ICar car = factory.createCar();car.show();}}
We can see that the caller also needs to instantiate the engine, chassis, and tires in order to assemble the car. The components of these cars are irrelevant to the caller and seriously violate the Demeter Law (there is no direct relationship, not within the class .), Coupling is too high. And is not conducive to expansion. In addition, the engine, chassis, and tires in this example are more specific. in actual application, the components of these products may also be abstract, and the caller does not know how to assemble the product. If the factory method is used, the entire architecture is much clearer.
When implementing the factory method, the client needs to decide which factory to instantiate for implementation. The factory method moves what you see but the logic inside the factory to the client. You need to modify the factory class, but now you only need to modify the client. Reduced coupling.