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原则

  • 相关阅读:
    grpc学习
    01
    样本1
    杀死长时间占用CPU的进程
    SWFTools pdf2swf 参数详解
    C#自动下载并保存文件示例
    Flex初始化时加载外部XML
    通过XPDF抽取PDF中的中文文本
    Flex操作Json数据示例
    C#下载文件和将文件转换为数据流下载的示例
  • 原文地址:https://www.cnblogs.com/oversea201405/p/3752186.html
Copyright © 2011-2022 走看看