zoukankan      html  css  js  c++  java
  • (转) java 简单工厂模式(实现一个计算器)

    package com.simpleFactory;
    
    /**
     * 运算类
     * @author Administrator
     *
     */
    public class Operation {
    
        
        private double numberA;
        
        private double numberB;
    
        
        public double getResultValue(){
            return 0.0;
        }
        
        public double getNumberA() {
            return numberA;
        }
    
        public void setNumberA(double numberA) {
            this.numberA = numberA;
        }
    
        public double getNumberB() {
            return numberB;
        }
    
        public void setNumberB(double numberB) {
            this.numberB = numberB;
        }
        
        
        
        
        
    }
    package com.simpleFactory;
    
    /**
     * 加法实现方式
     * @author Administrator
     *
     */
    public class Addition extends Operation {
    
        
        @Override
        public double getResultValue() {
            return getNumberA() + getNumberB();
        }
    }
    package com.simpleFactory;
    
    /**
     * 减法实现方式
     * @author Administrator
     *
     */
    public class Subtracter extends Operation {
    
        
        @Override
        public double getResultValue() {
            return getNumberA() - getNumberB();
        }
    }
    package com.simpleFactory;
    
    /**
     * 简单工厂类
     * @author Administrator
     *
     */
    public class SimpleFactory {
    
        private Operation operation;
        public Operation factoryOperate (String type ){
            
            if ("+".equals(type)){
                
                operation = new Addition();
            }
            else if ("-".equals(type)){
                
                operation = new Subtracter();
            }
         return operation;
        }
    }
    package com.simpleFactory;
    
    /**
     * 简单工厂类 ,利用反射实现
     * @author Administrator
     *
     */
    public class SimpleFactory_reflect {
    
        private Operation operation;
        public Operation factoryOperate (String classType ){
            
             try {
            operation = (Operation)Class.forName("com.simpleFactory."+classType).newInstance();
            } catch (Exception e) {
                
                e.printStackTrace();
            }
            
         return operation;
        }
    }

    重点的是在反射这里,通过反射机制可以不要在增加新功能时修改工厂类,只需要将新的方法函数名加进去就可以了。

  • 相关阅读:
    Microsoft EBooks
    JavaScript 数据访问(通译自High Performance Javascript 第二章) [转]
    time random sys os模块
    configparser logging collections 模块
    序列化模块和hashlib模块
    内置方法
    面向对象进阶
    property classmethod staticmethod的用法
    归一化设计,抽象类和接口类,接口隔离操作
    面向对象的三大属性
  • 原文地址:https://www.cnblogs.com/mrdoor/p/4068815.html
Copyright © 2011-2022 走看看