设计模式2-工厂模式
作者:互联网
在工厂方法模式中,核心的工厂类不再负责所有产品的创建,而是将具体创建工作交给子类去做。
一、go语言版
package main
import "fmt"
type Product interface {
Show(name string) string
}
type productA struct{}
func (*productA) Show(name string) string {
return fmt.Sprintf("MyProduct is %s", name)
}
type productB struct{}
func (*productB) Show(name string) string {
return fmt.Sprintf("MyProduct is %s", name)
}
type Factory interface {
CreateProduct() Product
}
type FactoryA struct{}
func (* FactoryA) CreateProduct() Product{
return &productA{}
}
type FactoryB struct{}
func (* FactoryB) CreateProduct() Product{
return &productB{}
}
func main() {
var fac Factory
fac = new(FactoryA)
pro := fac.CreateProduct()
s := pro.Show("A")
fmt.Printf("return is %v\n", s)
}
二、c++语言版
#include <iostream>
using namespace std;
class Product
{
public:
virtual void Show(string msg) = 0;
};
class ProductA : public Product
{
public:
void Show(string msg) {
cout << "ProductA show msg: " << msg << " " << endl;
}
};
class ProductB : public Product
{
public:
void Show(string msg) {
cout << "ProductB show msg: " << msg << " " << endl;
}
};
class Factory
{
public:
virtual Product *CreateProduct() = 0;
};
class FactoryA : public Factory
{
public:
Product *CreateProduct() {
return new ProductA();
}
};
class FactoryB : public Factory
{
public:
Product *CreateProduct() {
return new ProductB();
}
};
int main()
{
FactoryA fac;
Product *pro = fac.CreateProduct();
pro->Show("A is me");
delete pro;
}
三、c语言版
#include <stdio.h>
typedef struct _Product {
char name[64];
void (*show)(char *msg);
}Product;
void productA_show(char *msg)
{
printf("ProductA show msg %s\n", msg);
}
Product productA = {
.name = "product A",
.show = productA_show,
};
void productB_show(char *msg)
{
printf("ProductB show msg %s\n", msg);
}
Product productB = {
.name = "product B",
.show = productB_show,
};
typedef struct _ProductFactory {
Product *(*CreateProduct) ();
}ProductFactory;
Product *CreateProductA()
{
printf("Create Product A\n");
return &productA;
}
ProductFactory factoryA = {
.CreateProduct = CreateProductA,
};
Product *CreateProductB()
{
printf("Create Product B\n");
return &productB;
}
ProductFactory factoryB = {
.CreateProduct = CreateProductB,
};
int main()
{
Product *pro = factoryB.CreateProduct();
pro->show("is me");
return 0;
}
标签:Product,CreateProduct,show,模式,工厂,msg,return,设计模式,public 来源: https://blog.csdn.net/zgrztzy/article/details/120364347