工厂设计模式
工厂设计模式:
假设有一个人在工厂里生产牛奶(Milk),生产啤酒(Beer)
现在这个人想喝东西所以定义两种产品都同一个接口Drink
然后让所有产品都实现这个接口
interface Drink{
public void Drink(){}
} class Milk implement Drink{ public void Drink(){
System.out.println("喝牛奶");
} } class Beer implement Drink{ public void Drink(){
System.out.println("喝啤酒");
} }
public class App{
public static void main(String[] args) {
}
}
接下来再写一个工厂类
interface Drink{public void Drink();} class Milk implements Drink{ public void Drink(){ System.out.println("喝牛奶"); } } class Beer implements Drink{ public void Drink(){ System.out.println("喝啤酒"); } } class DrinkFactory{ public static Drink getInterface(String str){ if(str.equalsIgnoreCase("m")){ return new Milk(); }else if (str.equalsIgnoreCase("b")) { return new Beer(); }else{ return null; } } } public class App{ public static void main(String[] args) { } }
接下来就可以决定进行喝什么
interface Drink{public void Drink();} class Milk implements Drink{ public void Drink(){ System.out.println("喝牛奶"); } } class Beer implements Drink{ public void Drink(){ System.out.println("喝啤酒"); } } class DrinkFactory{ public static Drink getInterface(String str){ if(str.equalsIgnoreCase("m")){ return new Milk(); }else if (str.equalsIgnoreCase("b")) { return new Beer(); }else{ return null; } } } public class App{ public static void main(String[] args) { Drink milk=DrinkFactory.getInterface("m"); milk.Drink(); Drink beer=DrinkFactory.getInterface("b"); beer.Drink(); } }
然后完成了: