简单工厂模式和工厂方法模式
1. 简单工厂模式
publci class Sample{ .... } public class A extends Sample{ .... } public class B extends Sample{ ...... }
public class Factory{ //静态工厂方法,无必要再去实例化这个工厂类,增加没有必要的代码 public static Sample create(int which){ if(which==1) return new A(); if(which==2) return new B(); } }
Sample newSample=Factory.create(1);
public interface Plant{} public class PlantA implements Plant{ } public class PlantB implements Plant{ }
public interface Fruit{} public class FruitA implements Fruit{ } public class FruitB implements Fruit{ }
public interface AbstractFactory{ public Plant createPlant(); public Fruit creatFruit(); }
public Class FactoryA implements AbstractFactory{ public Plant createPlant(){ return new PlantA(); } public Fruit creatFruit(){ return new FruitA(); } }
public Class FactoryB implements AbstractFactory{ public Plant createPlant(){ return new PlantB(); } public Fruit creatFruit(){ return new FruitB(); } }
public class PlantC implements Plant{ } public class FruitC implements Fruit{ }
public Class FactoryC implements AbstractFactory{ public Plant createPlant(){ return new PlantC(); } public Fruit creatFruit(){ return new FruitC(); } }