通常實現git
public class WithOutEntityA { public WithOutEntityA(){ System.out.println("create WithOutEntityA ..."); } } public class WithOutEntityB { public WithOutEntityB(){ System.out.println("create WithOutEntityB ..."); } }
public static void main(String[] args) { new WithOutEntityA(); new WithOutEntityB(); }
create WithOutEntityA ... create WithOutEntityB ...
簡單/靜態工廠方法github
public interface IEntity { }
public class EntityA implements IEntity { public EntityA(){ System.out.println("create EntityA ..."); } } public class EntityB implements IEntity { public EntityB(){ System.out.println("create EntityB ..."); } }
public class SimpleFactory { public IEntity create(String type){ IEntity entity = null; if(type.equals("A")){ entity = new EntityA(); }else if(type.equals("B")){ entity = new EntityB(); } return entity; } }
public static void main(String[] args) { SimpleFactory simpleFactory = new SimpleFactory(); simpleFactory.create("A"); simpleFactory.create("B"); }
create EntityA ... create EntityB ...
工廠方法模式ide
public interface IEntity { }
定義具體產品類
public class EntityA implements IEntity { public EntityA(){ System.out.println("create EntityA ..."); } } public class EntityB implements IEntity { public EntityB(){ System.out.println("create EntityB ..."); } }
定義抽象工廠
public abstract class Factory { public abstract IEntity create(); }
定義具體工廠
public class FactoryA extends Factory{ @Override public IEntity create() { return new EntityA(); } } public class FactoryB extends Factory{ @Override public IEntity create() { return new EntityB(); } }
調用方法
public static void main(String[] args) { Factory factory = new FactoryA(); factory.create(); factory = new FactoryB(); factory.create(); }
輸出
create EntityA ... create EntityB ...
源碼code
https://github.com/Seasons20/DisignPattern.git
END對象