工厂方法模式分三中:简单工厂模式、工厂方法模式、抽象工厂模式
产品类:
interface ICar{void run();}public Class BMW implements ICar{public void run(){System.println("宝马跑100码");}}public Class LBJN implements ICar{public void run(){System.println("兰博基尼跑200码");}}
工厂类:
public Class CarFactory{public ICar createCar(int case){if(case == 100){return new BMW();}if(case == 200){return new LBJN();}}}
调用:
public Class Test{//创建工厂实例对象CarFactory factory = new CarFactory();//获取产品并且执行方法factory.createCar(200).run();}
产品类:
interface ICar{void run();}public Class BMW implements ICar{public void run(){System.println("宝马跑100码");}}public Class LBJN implementsICar{public void run(){System.println("兰博基尼跑200码");}}
工厂类:
//抽象工厂interface ICarFactory{ICar createCar();}//创建宝马的工厂public Class BMWFactory implements ICarFactory{ICar createCar(){return new BMW();}}//创建兰博基尼的工厂public Class LMJNFactory implements ICarFactory{ICar createCar(){return new LMJN();}}
调用:
public Class Test{//创建抽象工厂实例对象指向宝马factoryICarFactory factory = new BMWFactory();//获取产品并且执行方法factory.createCar().run();}
产品类:
//食品类产品族interface IFood{void eat();}public Class SummerFood implements IFood{void eat(){}}public Class WinnerFood implements IFood{void eat(){}}//衣服类产品族interface ICloths{void dress();}public Class SummerCloths implements ICloths{void dress(){}}public Class WinnerCloths implements ICloths{void dress(){}}
工厂类:
interface IFactory{IFood createFood();ICloths createCloths();-
} -
Public Class SummerFactory(){ IFood createFood(){return new SummerFood();}ICloths createCloths(){return new SummerCloths();}}Public Class WinnerFactory(){IFood createFood(){return new WinnerFood();}ICloths createCloths(){return new WinnerCloths();}}