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

1. 简单工厂模式

时间:2016-09-06 00:56:42      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

1.依据条件的不同,工厂类创建不同的实例。(有同一父类)

2.调用父类的方法。

3.因为不同的实例,所以会调用到子类的方法,得到不同的结果。  --->  利用多态

举例:

父类:

技术分享
public abstract class Operation {
    private double numberA;
    private double numberB;

    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;
    }

    public abstract double getResult();

}
View Code

4个子类:

技术分享
public class OperationAdd extends Operation {

    @Override
    public double getResult() {
        return getNumberA() + getNumberB();
    }

}
View Code
技术分享
public class OperationDiv extends Operation {

    @Override
    public double getResult() {
        return getNumberA() / getNumberB();
    }

}
View Code
技术分享
public class OperationMul extends Operation {

    @Override
    public double getResult() {
        return getNumberA() * getNumberB();
    }

}
View Code
技术分享
public class OperationSub extends Operation {

    @Override
    public double getResult() {
        return getNumberA() - getNumberB();
    }

}
View Code

工厂类:

技术分享
public class OperationFactory {
    public static Operation creatOperation(String operate) {
        Operation operation = null;
        switch (operate) {
        case "+":
            operation = new OperationAdd();
            break;
        case "-":
            operation = new OperationSub();
            break;
        case "*":
            operation = new OperationMul();
            break;
        case "/":
            operation = new OperationDiv();
            break;
        }
        return operation;
    }

}
View Code

使用:

public class jisuanqi {
    public static void main(String[] args) {

        Operation operation = OperationFactory.creatOperation("*");
        operation.setNumberA(2);
        operation.setNumberB(1);
        System.out.println(operation.getResult());
    }

}

 

1. 简单工厂模式

标签:

原文地址:http://www.cnblogs.com/H-BolinBlog/p/5844152.html

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