zoukankan      html  css  js  c++  java
  • 工厂方法

    github https://github.com/spring2go/core-spring-patterns

    定义

    • 定义一个用于创建对象的接口,让子类决定具体实例化哪个类。
    • Java中用得最多的模式之一

    关系图

    定义风扇接口

    public interface IFan {
    	
    	public void swithOn();
    	
    	public void switchOff();
    
    }
    

    台扇的具体实现

    public class TableFan implements IFan {
    
    	@Override
    	public void swithOn() {
    		System.out.println("The TableFan is swithed on ...");
    	}
    
    	@Override
    	public void switchOff() {
    		System.out.println("The TableFan is swithed off ...");
    	}
    
    }
    

    定义工厂的接口

    public interface IFanFactory {
    	IFan createFan();
    }
    

    台扇的工厂的具体实现

    
    public class TableFanFactory implements IFanFactory {
    
    	@Override
    	public IFan createFan() {
    		return new TableFan();
    	}
    
    }
    

    客户端调用

    public class FactoryMethodMain {
    
        public static void main(String[] args) {
    
            //需要哪个产品就 创建出哪产品的工厂
            IFanFactory fanFactory = new PropellerFanFactory();
    
            // 使用工厂方法创建一个电扇
            IFan fan = fanFactory.createFan();
    
            // 使用创建的对象
            fan.swithOn();
    
            fan.switchOff();
        }
    
    
    }
    

    好处

    • 客户和产品制造逻辑解耦
    • 遵循OCP,新需求无需改代码
    • 易于单元测试
      • 没有switch( or if/else)
    • 公共制造逻辑可以抽取到抽象类
      • 例如 BaseFanFactory

    Spring框架应用

    • Spring容器基于工厂模式
      • 创建Spring beans
      • 管理Spring beans生命周期
    • 工厂接口
      • BeanFactory
      • ApplicationContext
    • 工厂方法
      • getBean()

    总结

    1. 每增加一个具体的产品类,就增加一个相应工厂的实现类
    2. 简单工厂和工厂方法都只能制造一类产品
  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/zhangjianbin/p/9147379.html
Copyright © 2011-2022 走看看