工厂方法模式 — 设计模式

工厂方法模式(Factory Method Pattern) 是一种创建对象的设计模式。它属于创建型模式,定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法把类的实例化推迟到子类中进行。

例如,假设我们有一个汽车生产工厂的抽象概念。这个抽象工厂有一个生产汽车的方法(工厂方法),但是具体生产哪种汽车(轿车、SUV 或者跑车)由具体的工厂子类来决定。

https://kamacoder.com/problempage.php?pid=1076

go 复制代码
package main

import (
	"fmt"
)

// 积木接口
type IBuildBlock interface {
	Produce()
}

// 圆形积木
type CircleBlock struct{}

func (c *CircleBlock) Produce() {
	fmt.Println("Circle Block")
}

// 方形积木
type SquareBlock struct{}

func (s *SquareBlock) Produce() {
	fmt.Println("Square Block")
}

// 工厂接口
type IBlockFactory interface {
	ProduceWood() IBuildBlock
}

// 圆形积木工厂
type CircelBlockFactory struct{}

func (c *CircelBlockFactory) ProduceWood() IBuildBlock {
	return &CircleBlock{}
}

// 方形积木工厂
type SquareBlockFactory struct{}

func (s *SquareBlockFactory) ProduceWood() IBuildBlock {
	return &SquareBlock{}
}

type BlockFactory struct {
}

func (b *BlockFactory) ProduceBlockWood(factory IBlockFactory, count int) {
	for count > 0 {
		var block = factory.ProduceWood()
		block.Produce()
		count--
	}
}

func main() {
	var factory = &BlockFactory{}

	var n int
	fmt.Scan(&n)
	for n > 0 {
		var str string
		var count int
		fmt.Scan(&str, &count)
		if str == "Circle" {
			factory.ProduceBlockWood(&CircelBlockFactory{}, count)
		} else {
			factory.ProduceBlockWood(&SquareBlockFactory{}, count)
		}
		n--
	}
}
相关推荐
静水流深_沧海一粟13 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder13 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室21 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
BD_Marathon5 天前
工厂方法模式
android·java·工厂方法模式
青春易逝丶5 天前
工厂方法模式
工厂方法模式
holeer5 天前
【V3.0】「酒店 × 视觉AI」项目 | 需求分析说明书(软件工程概论 - 课程作业三)
人工智能·软件工程·需求分析·原型设计·总体设计·结构化设计
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式