首页 > 代码库 > C++设计模式从0进击-2-抽象工厂模式
C++设计模式从0进击-2-抽象工厂模式
Abstract Factory(抽象工厂模式):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
抽象工厂模式(Abstract Factory)
追MM少不了请吃饭了,麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西,虽然口味有所不同,但不管你带MM去麦当劳或肯德基,只管向服务员说“来四个鸡翅”就行了。麦当劳和肯德基就是生产鸡翅的Factory
工厂模式:客户类和工厂类分开。消费者任何时候需要某种产品,只需向工厂请求即可。消费者无须修改就可以接纳新产品。缺点是当产品修改时,工厂类也要做相应的修改。如:如何创建及如何向客户端提供。
//用户抽象接口class IUser{public: virtual void GetUser() = 0; virtual void InsertUser() = 0;};//部门抽象接口class IDepartment{public: virtual void GetDepartment() = 0; virtual void InsertDepartment() = 0;};//ACESS用户class CAccessUser: public IUser{public: virtual void GetUser() { cout << "Access GetUser" << endl; } virtual void InsertUser() { cout << "Access InsertUser" << endl; }};//ACCESS部门class CAccessDepartment: public IDepartment{public: virtual void GetDepartment() { cout << "Access GetDepartment" << endl; } virtual void InsertDepartment() { cout << "Access InsertDepartment" << endl; }};//SQL用户class CSqlUser: public IUser{public: virtual void GetUser() { cout << "Sql User" << endl; } virtual void InsertUser() { cout << "Sql Insert User" << endl; }};//SQL部门class CSqlDepartment: public IDepartment{public: virtual void GetDepartment() { cout << "Sql Department" << endl; } virtual void InsertDepartment() { cout << "Sql Insert Department" << endl; }};//抽象工厂class IFactory{public: virtual IUser * CreateUser() = 0; virtual IDepartment * CreateDepartment() = 0;};//ACCESS工厂class AccessFactory: public IFactory{public: virtual IUser * CreateUser() { return new CAccessUser(); } virtual IDepartment * CreateDepartment() { return new CAccessDepartment(); }};//SQL工厂class SQLFactory: public IFactory{public: virtual IUser * CreateUser() { return new CSqlUser(); } virtual IDepartment * CreateDepartment() { return new CSqlDepartment(); }};int _tmain(int argc, _TCHAR * argv[]){ IFactory * factory = new SQLFactory(); IUser * user = factory->CreateUser(); IDepartment * depart = factory->CreateDepartment(); user->GetUser(); depart->GetDepartment(); return 0;}
//关键点是
C++设计模式从0进击-2-抽象工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。