• 设计模式5:工厂方法模式


    在之前提到的简单方法模式中,如果需要给计算器添加一种运算,需要增加一个Operation子类,然后修改工厂类。

    这样的设计一方面简化了客户端的修改,另一方面需要修改工厂类,这是违反开放-封闭模式的。

    处理这种问题的另一种方法是工厂方法模式。

    工厂方法模式克服了违反开放-封闭的缺点,同时保持了封装对象创建过程的优点,但是带来的缺点是,需要新增一个工厂类+修改客户端代码以实现功能扩展。

    来看UML图:

    四种运算的子类是继承了Operation基类,每个子类都有一个对应的工厂类,封装了创建其实例的过程。

    代码:

    Operation及其子类:

    public abstract class Operation {
    	private double numA = 0;
    	private double numB = 0;
    	
    	public double getNumA() {
    		return numA;
    	}
    
    	public void setNumA(double numA) {
    		this.numA = numA;
    	}
    
    	public double getNumB() {
    		return numB;
    	}
    
    	public void setNumB(double numB) {
    		this.numB = numB;
    	}
    	
    	public abstract double getResult();
    }
    
    public class OperationAdd extends Operation {
    
    	@Override
    	public double getResult() {
    		return getNumA() + getNumB();
    	}
    
    }
    
    public class OperationDiv extends Operation {
    
    	@Override
    	public double getResult() {
    		// TODO Auto-generated method stub
    		return getNumA() / getNumB();
    	}
    
    }
    
    public class OperationMul extends Operation {
    
    	@Override
    	public double getResult() {
    		return getNumA() * getNumB();
    	}
    
    }
    
    public class OperationSub extends Operation {
    
    	@Override
    	public double getResult() {
    		// TODO Auto-generated method stub
    		return getNumA() - getNumB();
    	}
    
    }
    

    工厂接口和子类:

    public interface IFactory {
    	public Operation createOperation();
    }
    
    public class AddFactory implements IFactory {
    
    	@Override
    	public Operation createOperation() {
    		return new OperationAdd();
    	}
    
    }
    
    public class SubFactory implements IFactory {
    
    	@Override
    	public Operation createOperation() {
    		return new OperationSub();
    	}
    
    }
    
    public class MulFactory implements IFactory {
    
    	@Override
    	public Operation createOperation() {
    		return new OperationMul();
    	}
    
    }
    
    public class DivFactory implements IFactory {
    
    	@Override
    	public Operation createOperation() {
    		return new OperationDiv();
    	}
    
    }
    

    Demo:

    public class FactoryMethodDemo {
    	public static void main(String[] args) {
    		IFactory addFactory = new AddFactory();
    		Operation add = addFactory.createOperation();
    		add.setNumA(1.0);
    		add.setNumB(2.0);
    		System.out.println(add.getResult());
    	}
    }
    

      

  • 相关阅读:
    121. Best Time to Buy and Sell Stock
    玩转算法2.3常见的算法复杂度分析
    数组中的逆序对
    一些基本的代码模板
    230. Kth Smallest Element in a BST
    42. Trapping Rain Water
    api token
    仿百度查询
    baidu jsonp
    How to fix Error: laravel.log could not be opened?
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6671001.html
Copyright © 2020-2023  润新知