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

简单工厂模式

时间:2017-06-15 10:19:19      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:logs   工厂模式   ack   return   port   get   main   dev   运算   

 

Operator.java 类:

package sampleFactory;

import java.math.BigDecimal;

public abstract class Operator {
    BigDecimal numA;
    BigDecimal numB;
    BigDecimal result ;
    
    public abstract BigDecimal getResult();
}

OperatorAdd.java类

package sampleFactory;

import java.math.BigDecimal;

public class OperatorAdd extends Operator {
    @Override
    public BigDecimal getResult() {
        System.out.println(numA);
        System.out.println(numB);
        result = numA.add(numB);
        return result;
    }

}

OperatorDevide.java类

 

package sampleFactory;

import java.math.BigDecimal;

public class OperatorDevide extends Operator {
    @Override
    public BigDecimal getResult() {
        result = numA.divide(numB);
        return result;
    }

}

 

OperatorMul.java类

package sampleFactory;

import java.math.BigDecimal;

public class OperatorMul extends Operator {
    @Override
    public BigDecimal getResult() {
        result = numA.multiply(numB);
        return result;
    }

}

OperatorSub.java类

package sampleFactory;

import java.math.BigDecimal;

public class OperatorSub extends Operator {
    @Override
    public BigDecimal getResult() {
        result = numA.subtract(numB);
        return result;
    }

}

SampleFactory.java类

package sampleFactory;


public class SampleFactory {
    Operator op ;
    public Operator createOperator(String operator){
        switch(operator){
            case "+":
                op = new OperatorAdd();
                break;
            case "-":
                op = new OperatorSub();
                break;
            case "*":
                op = new OperatorMul();
                break;
            case "/":
                op = new OperatorDevide();
        }
        return op ;
    }

}

Business.java类

package sampleFactory;

import java.math.BigDecimal;
import java.util.Scanner;


public class Business {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数字A:"); 
        BigDecimal numA = sc.nextBigDecimal();
        System.out.println("请输入操作符:"); 
        String operator = sc.next();
        System.out.println("请输入数字B:"); 
        BigDecimal numB = sc.nextBigDecimal();
        SampleFactory sf = new SampleFactory();
        Operator op = sf.createOperator(operator);
        op.numA = numA ;
        op.numB = numB ;
        BigDecimal result = op.getResult();
        System.out.println("运算结果:"+result);
        sc.close();
    }

}

 

简单工厂模式

标签:logs   工厂模式   ack   return   port   get   main   dev   运算   

原文地址:http://www.cnblogs.com/ccgjava/p/7015544.html

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