基本设计模式06- 一般工厂模式

Posted perferect

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基本设计模式06- 一般工厂模式相关的知识,希望对你有一定的参考价值。

????一般工厂模式用的比较广,在Java中尤为常见,因为相对比较简单,所以使用场景比较广泛;
???? 例如在Springboot在整合RabbitMQ,创建EXCHANGE的代码,QUEUE的代码等都能看到。

1.一般工厂模式

1.1 基本概念

  定义一个创建对象的接口,让子类决定实例化哪个类。工厂类的方法,使一个类的初始化延迟到其子类。

1.2 UML图

技术图片

2. 结合 RabbitMQ中Exchange创建分析

2.1 代码分析

对象类接口

public abstract class AbstractExchange extends AbstractDeclarable implements Exchange {

工厂类

public final class ExchangeBuilder extends AbstractBuilder {
}

生成具体对象类过程

public <T extends Exchange> T build() {
		AbstractExchange exchange;
		if (ExchangeTypes.DIRECT.equals(this.type)) {
			exchange = new DirectExchange(this.name, this.durable, this.autoDelete, getArguments());
		}
		else if (ExchangeTypes.TOPIC.equals(this.type)) {
			exchange = new TopicExchange(this.name, this.durable, this.autoDelete, getArguments());
		}
		else if (ExchangeTypes.FANOUT.equals(this.type)) {
			exchange = new FanoutExchange(this.name, this.durable, this.autoDelete, getArguments());
		}
		else if (ExchangeTypes.HEADERS.equals(this.type)) {
			exchange = new HeadersExchange(this.name, this.durable, this.autoDelete, getArguments());
		}
		else {
			exchange = new CustomExchange(this.name, this.type, this.durable, this.autoDelete, getArguments());
		}
		exchange.setInternal(this.internal);
		exchange.setDelayed(this.delayed);
		exchange.setIgnoreDeclarationExceptions(this.ignoreDeclarationExceptions);
		exchange.setShouldDeclare(this.declare);
		if (!ObjectUtils.isEmpty(this.declaringAdmins)) {
			exchange.setAdminsThatShouldDeclare(this.declaringAdmins);
		}
		return (T) exchange;
	}

3.测试案例代码

要进行的操作

public class Operation {

    protected double numberA = 0 ;
    protected double numberB = 0;


    public void setNumberA(double numberA){
        this.numberA = numberA;
    }
    public double getNumberA(){
        return numberA;
    }
    public void setNumberB(double numberB){
        this.numberB = numberB;
    }

    public double getNumberB(){
        return numberB;
    }

    public double getResult(){
        double result = 0;
        return result;
    }

}

具体的操作类(可以有多个)

public class OperationAdd extends Operation{
    @Override
    public double getResult() {//重写方法
        double result = 0d;
        result = numberA + numberB;
        return result;
    }
}


工厂类

public class OperationFactory {
   public static Operation createOperation(String operation){
       Operation oper = null;
       switch(operation){
           case "+" :
               oper = new OperationAdd();break;
           case "-":
               oper = new OperationSub();break;
           case "*":
               oper = new OperationMul();break;
           case "/":
               oper = new OperationDiv();break;
       }
       return oper ;
   }

以上是关于基本设计模式06- 一般工厂模式的主要内容,如果未能解决你的问题,请参考以下文章

设计模式-工厂模式

设计模式抽象工厂模式(Abstract Factory)

PHP面向对象之选择工厂和更新工厂

C++工厂模式详解——设计模式

设计模式——工厂模式

设计模式之四-Factory模式