码迷,mamicode.com
首页 > 其他好文 > 详细

简单工厂模式

时间:2018-05-05 18:05:53      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:ase   代码   ret   abs   on()   operation   cas   default   style   

通过工厂来返回不同的对象,可使用同一种方法。

抽象类:

public abstract class Operation {
    private double numA;
    private double numB;
    private double result;
    
    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 AddOperation extends Operation {
    
    public double getResult() {
        
        return super.getNumA()+super.getNumB();
    }
    
}

public class SubOperation extends Operation  {
    public double getResult() {
        return super.getNumA()-super.getNumB();
    }
}

public class MulOperation extends Operation  {
    public double getResult() {
        return super.getNumA()*super.getNumB();
    }
}

public class DivOperation extends Operation {
    @Override
    public double getResult() {
        return super.getNumA()/super.getNumB();
    }
}

工厂类与实现:

public class OperationFactory {
    public  static  Operation createOperation(String type){
        switch (type) {
        case "+":
            return new AddOperation();
        case "-":
            return new SubOperation();
        case "*":
            return new MulOperation();
        case "/":
            return new DivOperation();
        default:
            break;
        }
        return null;
        
    }
    
    public static void main(String[] args) {
        Operation operation;
        operation=OperationFactory.createOperation("+");
        operation.setNumA(1);
        operation.setNumB(1);
        System.out.println(operation.getResult());
    }
}

这样通过控制显示层的代码即可控制整个实现逻辑。。。

 

简单工厂模式

标签:ase   代码   ret   abs   on()   operation   cas   default   style   

原文地址:https://www.cnblogs.com/blackdeng/p/8995247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!