0
点赞
收藏
分享

微信扫一扫

1、设计模式之简单工厂模式

Villagers 2022-09-28 阅读 92


问题描述:近期需要学习UML基础知识和23种设计模式相关知识,因此简单记录一下~

                   简单工厂模式实现及整理实现,基本原理参考:

​​https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/simple_factory.html#id2​​

​​https://www.runoob.com/design-pattern/factory-pattern.html​​

1、设计模式之简单工厂模式_linux

代码图实现:graphviz: ​​http://www.webgraphviz.com/​​

digraph G {      
node[shape=record]
{rank=same;Factory;Product}


Factory[ label="{Factory|\l|+createProductA():Product\l|+createProductB():Product\l}"]

Factory -> Product

Product[ label="{Product|\l| +show():void\l}"]


edge[ arrowhead="onormal", style="filled"]
ca[label="{ProductA|\l|+show():void\l}"]
cb[label="{ProductB|\l|+show():void\l}"]
{rank=same;ca;cb}
ca->Product
cb->Product

}

代码实现(简单工厂模式):

#include<iostream>
using namespace std;
enum CTYPE {COREA,COREB};

class product
{
public:
virtual void show()=0;
};

class productA:public product
{
public:
void show()
{
cout<<"factory A"<<endl;
}
};
class productB:public product
{
public:
void show()
{cout<<"factory B"<<endl;
}

};
class factory
{
public:
product *createproduct(enum CTYPE ctype)
{
if (ctype==COREA)
return new productA();
else if(ctype==COREB)
return new productB();

}

};
int main()
{
factory *A=new factory();
product *B=A->createproduct(COREA);
B->show();
if (A!=NULL)
{
delete A;
A=NULL;
}
if (B!=NULL)
{
delete B;
B=NULL;
}
return 0;
}

valgrind 内存检查有泄露~~`~(有时间在解决)

==18838== Memcheck, a memory error detector
==18838== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==18838== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==18838== Command: ./a.out
==18838== Parent PID: 18207
==18838==
==18838==
==18838== HEAP SUMMARY:
==18838== in use at exit: 72,704 bytes in 1 blocks
==18838== total heap usage: 4 allocs, 3 frees, 73,737 bytes allocated
==18838==
==18838== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==18838== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18838== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==18838== by 0x40106C9: call_init.part.0 (dl-init.c:72)
==18838== by 0x40107DA: call_init (dl-init.c:30)
==18838== by 0x40107DA: _dl_init (dl-init.c:120)
==18838== by 0x4000C69: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==18838==
==18838== LEAK SUMMARY:
==18838== definitely lost: 0 bytes in 0 blocks
==18838== indirectly lost: 0 bytes in 0 blocks
==18838== possibly lost: 0 bytes in 0 blocks
==18838== still reachable: 72,704 bytes in 1 blocks
==18838== suppressed: 0 bytes in 0 blocks
==18838==
==18838== For counts of detected and suppressed errors, rerun with: -v
==18838== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)


举报

相关推荐

0 条评论