Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use Factory Pattern

Shulou Source: shulou.com Published: 2022-06-01 11:53:04 09月26日 Update

这篇文章主要介绍"Factory Pattern怎么使用",在日常操作中,相信很多人在Factory Pattern怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Factory Pattern怎么使用"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

在软件工程中,设计模式(design pattern)是指对常见问题的通用解决方案。

Factory Pattern旨在解决对象创建的问题。

举一个例子,假设你要创建多种类型的玩具(例如toy tank,toy bus),需要先定义一个通用的基类,其拥有通用的方法(method )和数据(data)接口。

class TOY;// Common data memeberstring type;

// Common methods virtual function string get_type();endclass : TOY

然后对该基类进行扩展。

class TOY_Tank extends TOY;function new(); this.string = "Toy Tank";endfunction : new

string function string get_type(); return this.string;endfunction : get_typeendclass : TOY_Tank class TOY_Bus extends TOY;function new(); this.string = "Toy Bus";endfunction : new

string function string get_type(); return this.string;endfunction : get_typeendclass : TOY_Bus

到这里,我们完成了相关对象的创建工作。

下一个需要解决的问题是编写toy factory 类。为简单起见,考虑传递"1"以获得toy tank 的实例,传递"2"来从factory 获取toy bus 实例。

class TOY_factory;Toy my_toy// Common methodsfunction toy get_toy(int type); if(type == 1) this.my_toy = newTOY_Tank(); if(type == 2) this.my_toy = newTOY_Bus(); return this.my_toy;endfunction : get_toy

endclass : TOY_factory到此,关于"Factory Pattern怎么使用"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

Tags: Problems learning examples objects methods more help practical next examples multiple engineering common frequently asked questions interfaces data articles schemes patterns toys Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia OPPO Reno Huawei Shulou Tech Info MariaDB