码迷,mamicode.com
首页 > 其他好文 > 详细

抽象工厂

时间:2014-12-15 09:08:06      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:设计模式

 1,需求,为创建一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体类,简而言之对不同客户需求,生产出不同的产品

 2,具体demo类图,后面进行说明

bubuko.com,布布扣

3,具体代码:

//抽象工厂步骤
// 消费者不固定,工程不固定(工厂根据消费者动作)
// 实现消费者抽象类基类,消费者派生的实现,实例化就是消费者
// 操作的抽象基类,实现派生类各种操作,实例化的操作
// 工厂抽象类,抽象类包含两个抽象类,一个是消费者,一个是操作
// 抽象类实现了了工厂类的抽象,实例化的派生类实现工厂
#include "stdafx.h"
#include <iostream>

using namespace std;


class IUser{
public:
	virtual void setUser() = 0;
	virtual void getUser() = 0;
};


class SqlUser :public IUser{

public:
	void setUser(){
		cout << "SQL user set " << endl;
	}
	void getUser(){
		cout << "sql user get" << endl;
	}
};

class AccessUser :public IUser{
public:
	void setUser(){
		cout << "Access set user" << endl;
	}
	void getUser(){
		cout << "Access get User" << endl;
	}
};

class IDepartment{
public:
	virtual  void setDepartment() = 0;
	virtual void getDepartment() = 0;
};

class SqlDepartment :public IDepartment{
public:
	void setDepartment(){
		cout << "sql department set" << endl;
	}
	void getDepartment(){
		cout << "sql department get" << endl;
	}
};

class AccessDepartment :public IDepartment{
public:
	void setDepartment(){
		cout << "Access department set" << endl;
	}
	void getDepartment(){
		cout << "Access department get" << endl;
	}
};


class IFactory{
public:
	virtual IUser * createUser() = 0;
	virtual IDepartment *createDepartment() = 0;
};

class SqlFactory :public IFactory{
public:
	IUser* createUser(){
		return new SqlUser();
	}

	IDepartment * createDepartment(){
		return new SqlDepartment();
	}
};

class AccessFactory :public IFactory{
public:
	IUser* createUser(){
		return new AccessUser();
	}
	IDepartment * createDepartment(){
		return new AccessDepartment();
	}
};


class DataAccess{
private :
	static string db;
public:
	static IUser *createUser(){
		if (db=="access")
		{
			return new AccessUser();
		}
		if (db == "sql")
		{
			return new SqlUser();
		}
	}
	static IDepartment * createDepartment(){
		if (db=="access")
		{
			return new AccessDepartment();
		}
		if (db == "sql")
		{
			return new SqlDepartment();
		}
	}
};


string DataAccess::db = "sql";
int _tmain(int argc, _TCHAR* argv[])
{

	IFactory *factroy;  //抽象工厂
	IUser *user;   //抽象消费者
	IDepartment *department;  //工厂提供的操作

	factroy = new AccessFactory();   
	user = factroy->createUser();
	department = factroy->createDepartment();

	user->setUser();
	user->getUser();
	department->setDepartment();
	department->getDepartment();

	user = DataAccess::createUser();
	department = DataAccess::createDepartment();


	user->setUser();
	user->getUser();
	department->setDepartment();
	department->getDepartment();

	cin.get();



	return 0;
}
4,简介,其中代码中User等同于消费者,Department 实际性的操作,抽象工厂实质就是对与不同的消费者做出不同的行动。

5,白话延伸:就等同于你同时泡多个MM,由于每一MM有不同的特征和需求,吃饭的时候要带到不同地方吃饭


抽象工厂

标签:设计模式

原文地址:http://blog.csdn.net/sun734274006/article/details/41926101

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!