工厂模式
Posted demonycw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工厂模式相关的知识,希望对你有一定的参考价值。
工厂模式
Simple Factory
对于工厂模式而言,可能大家并不会陌生,顾名思义所谓工厂就是啥事都给你做了,顾客等着消费产品就好了,首先咋们就来聊聊这简单工厂模式的道道
废话不多说先上代码
Operation.java
public interface Operation {
public double getResult(double A, double B) throws Exception;
}
SimpleFactory.java
public class SimpleFactory {
private static Operation operation = null;
private static Operation add(){
System.out.println("add日志");
return new Add();
}
private static Operation subtract(){
System.out.println("subtract日志");
return new Subtract();
}
private static Operation multiply(){
System.out.println("multiply日志");
return new Multiply();
}
private static Operation divide(){
System.out.println("divide日志");
return new Divide();
}
public static Operation createOperation(String command){
/*
* @since 1.7 the param of switch can be String
* @before 1.7 the param of switch can be int,short,byte,char
* */
switch (command){
case "+":
operation = add();
break;
case "-":
operation = subtract();
break;
case "*":
operation = multiply();
break;
case "/":
operation = divide();
break;
default:
break;
}
return operation;
}
}
class Add implements Operation{
@Override
public double getResult(double A, double B) throws Exception {
return A+B;
}
}
class Subtract implements Operation{
@Override
public double getResult(double A, double B) throws Exception {
return A-B;
}
}
class Multiply implements Operation{
@Override
public double getResult(double A, double B) throws Exception {
return A*B;
}
}
class Divide implements Operation{
@Override
public double getResult(double A, double B) throws Exception {
if (B == 0){
throw new Exception("Divide by zero error");
}
return A/B;
}
}
Client.java
public class Client {
public static void main(String[] args) throws Exception {
Operation operation1 = SimpleFactory.createOperation("+");
System.out.println(operation1.getResult(33, 66));
Operation operation2 = SimpleFactory.createOperation("-");
System.out.println(operation2.getResult(33, 66));
Operation operation3 = SimpleFactory.createOperation("*");
System.out.println(operation3.getResult(3,6));
Operation operation4 = SimpleFactory.createOperation("/");
System.out.println(operation4.getResult(3,6));
System.out.println(operation4.getResult(3,0));
}
}
Run result
add日志
99.0
subtract日志
-33.0
multiply日志
18.0
divide日志
0.5
Exception in thread "main" java.lang.Exception: Divide by zero error
可见简单工厂模式的实现逻辑较为简单,从步骤上来讲,先写一个接口,然后写一堆操作类去实现接口中的getResult方法为创建对应的类作准备,然后在工厂的创建静态方法里做switch、case分支,由此可见,若要增加一个新的实现类就必须修改工厂类中的代码,虽然在客户端只用通过操作符创建对象而且还可以在工厂类里增加日志信息或者逻辑判断,但在工厂类的修改却相对繁琐,这也是简单工厂模式的缺点
以上是关于工厂模式的主要内容,如果未能解决你的问题,请参考以下文章
设计模式简单工厂模式 ( 简介 | 适用场景 | 优缺点 | 代码示例 )