Package com.lz.factory.simpleFactory;/** * Supplement: Object-oriented Principles * OCP: (open and closed principle) adding new features should not modify the original code, but instead add a new class * DIP: (Dependency Reversal Principle) dependency programming * LOD: (Dimitri Law) reduces coupling, communicates only with necessary objects * Static Factory class {* Creator and Separation of callers * Simple factory problem: Adding a new feature requires a code change *} * Factory method class {* Code too Much *} * Comparison of the two * simple factory structure Code simpler * Factory method is more difficult to maintain * Summary: The factory method model conforms to the theoretical requirements but the actual use of more simple Factory mode selection * */ Public classSimplefactory { Public StaticCar Createcar (String msg) {if(Msg.equals ("Jeep")) { return NewJeep (); } Else if(Msg.equals ("BMW")) { return NewBMW (); } Else { return NULL; } }}
Package com.lz.factory.simpleFactory; /* * Automotive Interface */ Public Interface Car { publicvoid run ();}
package com.lz.factory.simpleFactory; public class BMW implements car{@Override public
void
run () {System.
out . println (
"
i am BWM
"
); }}
Package com.lz.factory.simpleFactory; Public class Jeep implements car{ @Override publicvoid run () { System. out. println ("I am Jeep");} }
Package com.lz.factory.simpleFactory; Public classTest01 { Public Static voidMain (string[] args) {Car BMW=NewBMW (); Car Jeep=NewJeep (); Bmw.run (); Jeep.run (); Car BMW1= Simplefactory.createcar ("BMW"); Car Jeep1= Simplefactory.createcar ("Jeep"); Bmw1.run (); Jeep1.run (); }}
Factory Method Class:
Add a factory method to each of the classes
Package Com.lz.factory.factoryMethod; /* */Publicinterface carfactory { Car createcar ();}
Java design mode GOF23 02 Factory mode