工厂设计模式

工厂设计模式:

假设有一个人在工厂里生产牛奶(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();
	}
}

然后完成了:

 

posted @ 2018-01-03 15:03  香菇炖小鸡  阅读(154)  评论(0编辑  收藏  举报