设计模式2-工厂模式

在工厂方法模式中,核心的工厂类不再负责所有产品的创建,而是将具体创建工作交给子类去做。

../_images/loger.jpg

一、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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值