zoukankan      html  css  js  c++  java
  • 工厂方法模式--结合具体例子学习工厂方法模式

    在学习工厂方法模式之前,可以先学习一下简单工厂模式,网址是http://blog.csdn.net/u012116457/article/details/21650421,这里仍以水果的实例讲解。

    先来说说简单工厂模式的特点,简单工厂模式将具体类的创建交给了工厂,使客户端不再直接依赖于产品,但是其违背了OCP原则,当对系统进行扩展时,仍然需要去修改原有的工厂类的代码。

    而工厂方法模式则解决了这一问题,在工厂方法模式中,核心工厂类不再负责产品的创建,而把其延迟到其子类当中,核心工厂类仅仅为其子类提供必要的接口。

    现在,结合下面的例子具体的理解一下工厂方法模式:

    interface Fruit{
    	public String tell();
    }
    interface Factory{
    	public Fruit getFruit();
    } 
    
    //苹果类
    class Apple implements Fruit{
    	public String tell(){
    		return "我是苹果";
    	}
    }
    //香蕉类
    class Banana implements Fruit{
    	public String tell(){
    		return "我是香蕉";
    	}
    } 
    class AppleFactory implements Factory{
    	public Fruit getFruit(){
    		return new Apple();
    	}
    }
    class BananaFactory implements Factory{
    	public Fruit getFruit(){
    		return new Banana();
    	}
    }
    public class Store {
    	public static void main(String[] args) {
           Fruit f= null; 
           Factory factory = null;
           
           factory=new AppleFactory();  
           f=  factory.getFruit();   
           System.out.println( f.tell());   
           
           factory=new BananaFactory();  
           f=factory.getFruit();  
           System.out.println( f.tell());	}
    }
    
    


     

    定义一个工厂接口,让具体的工厂类去实现它,从代码中不难看出,当对代码进行扩展时,比如要加入一个Grape类,只需要定义一个Grape类,并定义一个Grape的工厂类GrapeFactory去继承工厂接口即可,而不必对原有的代码进行修改,完全符合OCP原则

  • 相关阅读:
    使用canvas实现擦玻璃效果
    安装jdk For Windows
    墙裂推荐4款js网页烟花特效
    再次推荐一款逼真的HTML5下雪效果
    HTML5播放暂停音乐
    周末web前端练习
    Javascript贪食蛇小游戏
    jquery实现更多内容效果
    jQuery省市区三级联动插件
    Web前端测试题
  • 原文地址:https://www.cnblogs.com/oversea201405/p/3752186.html
Copyright © 2011-2022 走看看