• 工厂设计模式


    工厂设计模式:

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

    然后完成了:

  • 相关阅读:
    Linux搭建iscsi服务,客户端(Linux&Win XP)挂载使用
    SecucreCRT安装与破解
    最全的HCIA-R&S实验笔记
    AtCoder Grand Contest 036
    Comet OJ CCPC-Wannafly & Comet OJ 夏季欢乐赛(2019)
    2019慈溪集训小记
    Codeforces Round #573 (Div. 1)
    Comet OJ
    Codeforces Round #576 (Div. 1)
    Codechef August Challenge 2019 Division 2
  • 原文地址:https://www.cnblogs.com/zyn0216/p/8183802.html
Copyright © 2020-2023  润新知