Go和Java实现工厂方法模式

发布时间:2023年12月26日

Go和Java实现工厂方法模式

本文通过计算器案例来说明工厂方法模式的使用,使用Go语言和Java语言实现。

1、工厂方法模式

工厂方法模式是最常用的设计模式之一,这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方

式。

在工厂方法模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建

的对象。

  • 意图:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂方法模式使其创建过程延迟到

    子类进行。

  • 主要解决:主要解决接口选择的问题。

  • 何时使用:我们明确地计划不同条件下创建不同实例时。

  • 如何解决:让其子类实现工厂接口,返回的也是一个抽象的产品。

  • 关键代码:创建过程在其子类执行。

  • 应用实例:1、您需要一辆汽车,可以直接从工厂里面提货,而不用去管这辆汽车是怎么做出来的,以及这个

    汽车里面的具体实现。 2、Hibernate 换数据库只需换方言和驱动就可以。

  • 优点:1、一个调用者想创建一个对象,只要知道其名称就可以了。 2、扩展性高,如果想增加一个产品,只

    要扩展一个工厂类就可以。 3、屏蔽产品的具体实现,调用者只关心产品的接口。

  • 缺点:每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定

    程度上增加了系统的复杂度,同时也增加了系统具体类的依赖。这并不是什么好事。

  • 使用场景:1、日志记录器:记录可能记录到本地硬盘、系统事件、远程服务器等,用户可以选择记录日志到

    什么地方。 2、数据库访问,当用户不知道最后系统采用哪一类数据库,以及数据库可能有变化时。 3、设计

    一个连接服务器的框架,需要三个协议,“POP3”、“IMAP”、“HTTP”,可以把这三个作为产品类,共同实现一

    个接口。

  • 注意事项:作为一种创建类模式,在任何需要生成复杂对象的地方,都可以使用工厂方法模式。有一点需要注

    意的地方就是复杂对象适合使用工厂方法模式,而简单对象,特别是只需要通过 new 就可以完成创建的对

    象,无需使用工厂方法模式。如果使用工厂方法模式,就需要引入一个工厂类,会增加系统的复杂度。

  • 适用性:1、当一个类不知道它所必须创建的对象的类的时候。2、当一个类希望由它的子类来指定它所创建

    的对象的时候。3、当类将创建对象的职责委托给多个帮助子类中的某一个,并且类希望将哪一个帮助子类是

    代理者这一信息局部化的时候。

简单说工厂方法模式就是为了提供代码结构的扩展性,屏蔽每?个功能类中的具体实现逻辑,让外部可以更加简单

的只是知道调?即可,同时这也是去掉众多 ifelse 的?式。

2、Go实现简单计算器

下面实现一个简单的计算器,包含简单的加减乘除功能。

package factory

// 这里实现一个简单的计算器
// 计算接口,包含计算数的设置和结果的计算
type Operation interface {
	// 设置进行计算的两个数
	SetNumberA(float64)
	SetNumberB(float64)
	// 计算
	Calculate() (float64, error)
}
package factory

// ============加法===========
type AddOperation struct {
	// 包含两个操作数
	numberA float64
	numberB float64
}

func (addOperation *AddOperation) Calculate() (float64, error) {
	return addOperation.numberA + addOperation.numberB, nil
}

func (addOperation *AddOperation) SetNumberA(numberA float64) {
	addOperation.numberA = numberA
}

func (addOperation *AddOperation) SetNumberB(numberB float64) {
	addOperation.numberB = numberB
}
package factory

// ============减法============
type SubOperation struct {
	// 包含两个操作数
	numberA float64
	numberB float64
}

func (subOperation *SubOperation) Calculate() (float64, error) {
	return subOperation.numberA - subOperation.numberB, nil
}

func (subOperation *SubOperation) SetNumberA(numberA float64) {
	subOperation.numberA = numberA
}

func (subOperation *SubOperation) SetNumberB(numberB float64) {
	subOperation.numberB = numberB
}
package factory

// ============乘法============
type MulOperation struct {
	// 包含两个操作数
	numberA float64
	numberB float64
}

func (mulOperation *MulOperation) Calculate() (float64, error) {
	return mulOperation.numberA * mulOperation.numberB, nil
}

func (mulOperation *MulOperation) SetNumberA(numberA float64) {
	mulOperation.numberA = numberA
}

func (mulOperation *MulOperation) SetNumberB(numberB float64) {
	mulOperation.numberB = numberB
}
package factory

import "errors"

// ============除法============
type DivOperation struct {
	// 包含两个操作数
	numberA float64
	numberB float64
}

func (divOperation *DivOperation) Calculate() (float64, error) {
	if divOperation.numberB == 0 {
		return -1, errors.New("被除数不能为0")
	} else {
		return divOperation.numberA / divOperation.numberB, nil
	}
}

func (divOperation *DivOperation) SetNumberA(numberA float64) {
	divOperation.numberA = numberA
}

func (divOperation *DivOperation) SetNumberB(numberB float64) {
	divOperation.numberB = numberB
}
package constant

const (
	Add = "+"
	Sub = "-"
	Mul = "*"
	Div = "/"
)
package factory

import "proj/constant"

// ============工厂接口============
type OperationFactory interface {
	CreateOperate() Operation
}

// ============加法工厂类============
type AddFactory struct {
}

func (addFactory *AddFactory) CreateOperate() Operation {
	return &AddOperation{}
}

// ============减法工厂类============
type SubFactory struct {
}

func (subFactory *SubFactory) CreateOperate() Operation {
	return &SubOperation{}
}

// ============乘法工厂类============
type MulFactory struct {
}

func (mulFactory *MulFactory) CreateOperate() Operation {
	return &MulOperation{}
}

// ============除法工厂类============
type DivFactory struct {
}

func (divFactory *DivFactory) CreateOperate() Operation {
	return &DivOperation{}
}


// 用一个简单工厂封装工厂方法
type OperationFactoryCreate struct {
}

func (operationFactoryCreate *OperationFactoryCreate) NewOperationFactory(operate string) OperationFactory {
	switch operate {
	case constant.Add:
		return &AddFactory{}
	case constant.Sub:
		return &SubFactory{}
	case constant.Mul:
		return &MulFactory{}
	case constant.Div:
		return &DivFactory{}
	}
	return nil
}
package main

import (
	"fmt"
	"proj/constant"
)

import . "proj/factory"

// 测试
func main() {

	// 全局变量
	var numberA float64 = 200
	var numberB float64 = 100
	var operationFactory OperationFactory
	var operation Operation
	var result float64
	var err error

	// ============加法============
	operationFactory = &AddFactory{}
	operation = operationFactory.CreateOperate()
	operation.SetNumberA(numberA)
	operation.SetNumberB(numberB)
	result, err = operation.Calculate()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Add Result:", result)
	}

	// ============减法============
	operationFactory = &SubFactory{}
	operation = operationFactory.CreateOperate()
	operation.SetNumberA(numberA)
	operation.SetNumberB(numberB)
	result, err = operation.Calculate()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Sub Result:", result)
	}

	// ============乘法============
	operationFactory = &MulFactory{}
	operation = operationFactory.CreateOperate()
	operation.SetNumberA(numberA)
	operation.SetNumberB(numberB)
	result, err = operation.Calculate()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Mul Result:", result)
	}

	// ============除法============
	operationFactory = &DivFactory{}
	operation = operationFactory.CreateOperate()
	operation.SetNumberA(numberA)
	operation.SetNumberB(numberB)
	result, err = operation.Calculate()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Div Result:", result)
	}

	fmt.Println("========================")

	// 简单工厂封装工厂方法
	operationFactoryCreate := OperationFactoryCreate{}

	// ============加法============
	operationFactory = operationFactoryCreate.NewOperationFactory(constant.Add)
	operation = operationFactory.CreateOperate()
	operation.SetNumberA(numberA)
	operation.SetNumberB(numberB)
	result, err = operation.Calculate()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Add Result:", result)
	}

	// ============减法============
	operationFactory = operationFactoryCreate.NewOperationFactory(constant.Sub)
	operation = operationFactory.CreateOperate()
	operation.SetNumberA(numberA)
	operation.SetNumberB(numberB)
	result, err = operation.Calculate()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Sub Result:", result)
	}

	// ============乘法============
	operationFactory = operationFactoryCreate.NewOperationFactory(constant.Mul)
	operation = operationFactory.CreateOperate()
	operation.SetNumberA(numberA)
	operation.SetNumberB(numberB)
	result, err = operation.Calculate()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Mul Result:", result)
	}

	// ============除法============
	operationFactory = operationFactoryCreate.NewOperationFactory(constant.Div)
	operation = operationFactory.CreateOperate()
	operation.SetNumberA(numberA)
	operation.SetNumberB(numberB)
	result, err = operation.Calculate()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Div Result:", result)
	}
}
# 程序输出
Add Result: 300
Sub Result: 100
Mul Result: 20000
Div Result: 2
========================
Add Result: 300
Sub Result: 100
Mul Result: 20000
Div Result: 2

3、Java实现简单计算器

package com.factory;

// 这里实现一个简单的计算器
// 计算接口,包含计算数的设置和结果的计算
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 Calculate();
}
package com.factory;

// ============加法===========
public class AddOperation extends Operation {

    @Override
    public double Calculate() {
        return this.getNumberA() + this.getNumberB();
    }
}
package com.factory;

// ============减法============
public class SubOperation extends Operation {

    @Override
    public double Calculate() {
        return this.getNumberA() - this.getNumberB();
    }
}
package com.factory;

// ============乘法============
public class MulOperation extends Operation {

    @Override
    public double Calculate() {
        return this.getNumberA() * this.getNumberB();
    }
}
package com.factory;

// ============除法============
public class DivOperation extends Operation {

    @Override
    public double Calculate() {
        if (this.getNumberB() == 0) {
            throw new RuntimeException("被除数不能为0!");
        } else {
            return this.getNumberA() / this.getNumberB();
        }
    }
}
package com.factory;

public enum OperationType {
    ADD, SUB, MUL, DIV;
}
package com.factory;

// ============工厂接口============
public interface OperationFactory {
    Operation CreateOperate();
}
package com.factory;

// ============加法工厂类============
public class AddFactory implements OperationFactory {

    @Override
    public Operation CreateOperate() {
        return new AddOperation();
    }
}
package com.factory;

// ============减法工厂类============
public class SubFactory implements OperationFactory {

    @Override
    public Operation CreateOperate() {
        return new SubOperation();
    }
}
package com.factory;

// ============乘法工厂类============
public class MulFactory implements OperationFactory{

    @Override
    public Operation CreateOperate() {
        return new MulOperation();
    }
}
package com.factory;

// ============除法工厂类============
public class DivFactory implements OperationFactory {

    @Override
    public Operation CreateOperate() {
        return new DivOperation();
    }
}
package com.factory;

// 用一个简单工厂封装工厂方法
// ============工厂类============
public class OperationFactoryCreate {

    public OperationFactory NewOperationFactory(OperationType operate) {
        switch (operate) {
            case ADD:
                return new AddFactory();
            case SUB:
                return new SubFactory();
            case MUL:
                return new MulFactory();
            case DIV:
                return new DivFactory();
        }
        return null;
    }
}
package com.factory;

public class Test {

    public static void main(String[] args) {

        // 全局变量
        Operation operation = null;
        double result = 0;
        OperationFactory operationFactory = null;

        // ============加法============
        operationFactory = new AddFactory();
        operation = operationFactory.CreateOperate();
        operation.setNumberA(200);
        operation.setNumberB(100);
        result = operation.Calculate();
        System.out.println("result :" + result);

        // ============减法============
        operationFactory = new SubFactory();
        operation = operationFactory.CreateOperate();
        operation.setNumberA(200);
        operation.setNumberB(100);
        result = operation.Calculate();
        System.out.println("result :" + result);

        // ============乘法============
        operationFactory = new MulFactory();
        operation = operationFactory.CreateOperate();
        operation.setNumberA(200);
        operation.setNumberB(100);
        result = operation.Calculate();
        System.out.println("result :" + result);

        // ============除法============
        operationFactory = new DivFactory();
        operation = operationFactory.CreateOperate();
        operation.setNumberA(200);
        operation.setNumberB(100);
        result = operation.Calculate();
        System.out.println("result :" + result);

        System.out.println("========================");

        // 简单工厂封装工厂方法
        OperationFactoryCreate operationFactoryCreate = new OperationFactoryCreate();

        // ============加法============
        operationFactory = operationFactoryCreate.NewOperationFactory(OperationType.ADD);
        operation = operationFactory.CreateOperate();
        operation.setNumberA(200);
        operation.setNumberB(100);
        result = operation.Calculate();
        System.out.println("result :" + result);

        // ============减法============
        operationFactory = operationFactoryCreate.NewOperationFactory(OperationType.SUB);
        operation = operationFactory.CreateOperate();
        operation.setNumberA(200);
        operation.setNumberB(100);
        result = operation.Calculate();
        System.out.println("result :" + result);

        // ============乘法============
        operationFactory = operationFactoryCreate.NewOperationFactory(OperationType.MUL);
        operation = operationFactory.CreateOperate();
        operation.setNumberA(200);
        operation.setNumberB(100);
        result = operation.Calculate();
        System.out.println("result :" + result);

        // ============除法============
        operationFactory = operationFactoryCreate.NewOperationFactory(OperationType.DIV);
        operation = operationFactory.CreateOperate();
        operation.setNumberA(200);
        operation.setNumberB(100);
        result = operation.Calculate();
        System.out.println("result :" + result);

    }
}
# 程序输出
result :300.0
result :100.0
result :20000.0
result :2.0
========================
result :300.0
result :100.0
result :20000.0
result :2.0
文章来源:https://blog.csdn.net/qq_30614345/article/details/130352543
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。