设计模式篇

//一、工本模式

#include<iostream>
#include<string>
using namespace std;

class Shape {
	public:
	virtual void draw()=0;
};

class Square:public Shape
{
	public:
	void draw(){
		cout<<"Inside Square::draw() method."<<endl;
	}
};

class Circle:public Shape
{
	public:
	void draw(){
		cout<<"Inside Circle::draw() method."<<endl;
	}
};

class Rectangle:public Shape
{
	public:
	void draw(){
		cout<<"Inside Rectangle::draw() method."<<endl;
	}
};

class ShapeFactory{
	public:
	Shape * getShape(string shapeType="")
	{
		if(shapeType.length() == 0) return nullptr;
		else if(shapeType == "CIRCLE") return new Circle();
		else if(shapeType == "RECTANGLE") return new Rectangle();
		else if(shapeType == "SQUARE") return new Square();

		return nullptr;
	}
};

int main()
{
	ShapeFactory shapeFactory;

	Shape *shape=nullptr;

	shape=shapeFactory.getShape("CIRCLE");
	shape->draw();

	shape=shapeFactory.getShape("RECTANGLE");
	shape->draw();

	shape=shapeFactory.getShape("SQUARE");
	shape->draw();

	return 0;
}

//二、抽象工厂模式

#include<iostream>
#include<string>
using namespace std;

class Shape{
	public:
		virtual void draw()=0;
};

class Rectangle:public Shape
{
	public:
		void draw()
		{
			cout<<"Inside Rectangle::draw() method."<<endl;
		}
};


class Square:public Shape
{
	public:
		void draw()
		{
			cout<<"Inside Square::draw() method."<<endl;
		}
};

class Circle:public Shape
{
	public:
		void draw()
		{
			cout<<"Inside Circle::draw() method."<<endl;
		}
};


class Color{
	public:
		virtual void fill()=0;
};

class Red:public Color{
	public:
		void fill()
		{
			cout<<"Inside Red::fill() method."<<endl;
		}
};

class Green:public Color{
	public:
		void fill()
		{
			cout<<"Inside Green::fill() method."<<endl;
		}
};

class Blue:public Color{
	public:
		void fill()
		{
			cout<<"Inside Blue::fill() method."<<endl;
		}
};

class AbstractFactory{
	public:
		virtual Color* getColor(string color)=0;
		virtual Shape* getShape(string shape)=0;
};

class ShapeFactory:public AbstractFactory{
	public:
		Shape* getShape(string shapetype)
		{
			if(shapetype.length()==0) return nullptr;
			else if(shapetype == "CIRCLE") return new Circle();
			else if(shapetype == "RECTANGLE") return new Rectangle();
			else if(shapetype == "SQUARE") return new Square();

			return nullptr;
		}

		Color* getColor(string color)
		{
			return nullptr;
		}
};

class ColorFactory:public AbstractFactory{
	public:
		Shape* getShape(string shapetype)
		{
			return nullptr;
		}

		Color* getColor(string color)
		{
			if(color.length()==0) return nullptr;
			else if(color == "RED") return new Red();
			else if(color == "GREEN") return new Green();
			else if(color == "BLUE") return new Blue();

			return nullptr;
		}
};

class FactoryProducer{
	public:
		static	AbstractFactory * getFactory(string choice)
		{
			if(choice == "SHAPE") return new ShapeFactory();
			else if(choice == "COLOR") return new ColorFactory();

			return nullptr;
		}

};


int main()
{
	AbstractFactory *abstractfactory=nullptr;

	/* ---获取对象形状----- */
	abstractfactory=FactoryProducer::getFactory("SHAPE");

	Shape* shape = abstractfactory->getShape("CIRCLE");
	shape->draw();

	shape = abstractfactory->getShape("RECTANGLE");
	shape->draw();

	shape = abstractfactory->getShape("SQUARE");
	shape->draw();
	/*------获取对象颜色------ */
	abstractfactory=FactoryProducer::getFactory("COLOR");

	Color* color = abstractfactory->getColor("RED");
	color->fill();

	color = abstractfactory->getColor("GREEN");
	color->fill();

	color = abstractfactory->getColor("BLUE");
	color->fill();

	return 0;
}

//三、单例模式


#include<iostream>
#include<string>
using namespace std;

class SingleObject{
	private:
		SingleObject(){};
	public:
		static SingleObject * getInstance(){
			static SingleObject instance;
			return &instance;
		}

	void showMessage()
	{
		cout<<"Hello, World!"<<endl;
	}

};

int main()
{
	SingleObject *object =nullptr;
	//object = new SingleObject();   //构造函数私有,无法通过此方法实例化对象

	object =SingleObject::getInstance();
	object->showMessage();
	return 0;
}

//四、建造者模式

#include<iostream>
#include<string>
#include<list>

using namespace std;

class Packing{
	public:
		virtual string pack()=0;
};

class Wrapper:public Packing{
	public:
		string pack(){
			return "Wrapper";
		}
};

class Bottle:public Packing{
	public:
		string pack(){
			return "Bottle";
		}
};

class Item{
	public:
		virtual string name()=0;
		virtual Packing* packing()=0;
		virtual float price()=0;
};

class Burger:public Item{
	public:
	Packing* packing(){
		return new Wrapper();
	}
};

class ColdDrink:public Item{
	public:
		Packing* packing(){
			return new Bottle();
		}
};

class VegBurger:public Burger{
	public:
		float price(){
			return 25.0f;
		}
		string name(){
			return "Veg Burger";
		}
};

class ChickenBurger:public Burger{
	public:
		float price(){
			return 50.5f;
		}
		string name(){
			return "Chicken Burger";
		}
};

class Coke:public ColdDrink{
	public:
		float price(){
			return 30.0f;
		}
		string name(){
			return "Coke";
		}
};

class Pepsi:public ColdDrink{
	public:
		float price(){
			return 35.0f;
		}
		string name()
		{
			return "Pepsi";
		}
};

class Meal{
	public:
		void addItem(Item* item){
			items.push_back(item);
		}

		float getCost(){
			float cost = 0.0f;
			for(auto item:items){
				cost += item->price();
			}
			return cost;
		}

		void showItems(){
			for(auto item:items){
				cout<<"Item:"<<item->name()<<",";
				cout<<"Paking:"<<item->packing()->pack()<<",";
				cout<<"Price:"<<item->price();
				cout<<endl;
			}
		}

	private:
		list<Item*>items;
};

class MealBuilder{
	public:
		Meal* prepareVegMeal(){
			Meal * meal =new Meal();
			meal->addItem(new VegBurger());
			meal->addItem(new Coke());
			return meal;
		}

		Meal* prepareNonVegMeal(){
			Meal *meal=new Meal();
			meal->addItem(new ChickenBurger());
			meal->addItem(new Pepsi());
			return meal;
		}
};

int main()
{
	MealBuilder* mealBuilder = new MealBuilder();

	Meal *vegMeal = mealBuilder->prepareVegMeal();
	cout<<"Veg Meal"<<endl;
	vegMeal->showItems();
	cout<<"Total Cost:"<<vegMeal->getCost();
	cout<<endl<<endl;

	Meal *nonVegMeal = mealBuilder->prepareNonVegMeal();
	cout<<"Non-veg Meal"<<endl;
	nonVegMeal->showItems();
	cout<<"Total Cost:"<<nonVegMeal->getCost();
	cout<<endl;

	return 0;
}

//五、适配器模式

#include<iostream>
#include<string>
using namespace std;

//为媒体播放器和更高级的媒体播放器创建接口
class MediaPlayer{
	public:
		virtual void play(string audioType, string fileName)=0;
};

class AdvancedMediaPlayer{
	public:
	virtual void playVlc(string fileName){}
	virtual void playMp4(string fileName){}
};

//创建实现AdvanedMediaPlayer接口实体类
class VlcPlayer:public AdvancedMediaPlayer{
	public:
		void playVlc(string fileName){
			cout<<"Playing vlc file. Name:"<<fileName<<endl;
		}
};

class Mp4Player:public AdvancedMediaPlayer{
	public:
		void playMp4(string fileName){
			cout<<"Playing mp4 file. Name:"<<fileName<<endl;
		}
};

//创建实现了MediaAdaper接口的适配器类
class MediaAdapter:public MediaPlayer{
	public:
		MediaAdapter(string audioType){
			if(audioType=="vlc")
			{
				advancedMusicPlayer=new VlcPlayer();
			}
			else if(audioType=="mp4")
			{
				advancedMusicPlayer=new Mp4Player();
			}
		}

		void play(string audioType, string fileName){
			if(audioType=="vlc")
			{
				advancedMusicPlayer->playVlc(fileName);
			}
			else if(audioType=="mp4")
			{
				advancedMusicPlayer->playMp4(fileName);
			}
		}

	private:
		AdvancedMediaPlayer *advancedMusicPlayer;

};

//创建实现了MediaPlayer接口的实体类
class AudioPlayer:public MediaPlayer{
	public:
		void play(string audioType, string fileName){
			if(audioType=="mp3"){
				cout<<"Playing mp3 file. Name:"<<fileName<<endl;
			}
			else if((audioType=="vlc")|| (audioType=="mp4")){
				mediaAdapter=new MediaAdapter(audioType);
				mediaAdapter->play(audioType, fileName);
			}
			else
			{
				cout<<"Invalid media."<<audioType<<"format not supported"<<endl;
			}
		}
	private:
		MediaAdapter *mediaAdapter;
};

int main()
{
	AudioPlayer *audioPlayer=new AudioPlayer();

	audioPlayer->play("mp3","Beyond the horizon.mp3");
	audioPlayer->play("mp4","alone.mp4");
	audioPlayer->play("vlc","far far away.vlc");
	audioPlayer->play("mp3","mind me.avi");

	return 0;
}

六、桥接模式

#include<iostream>
#include<string>
using namespace std;

class DrawAPI{
	public:
		virtual void drawCircle(int radius,int x,int y)=0;
};

class RedCircle:public DrawAPI{
	public:
		void drawCircle(int radius,int x,int y){
			cout<<"Drawing Circle[color:red,radius:"<<radius<<",x:"
				<<x<<",y:"<<y<<"]"<<endl;
		}
};


class GreenCircle:public DrawAPI{
	public:
		void drawCircle(int radius,int x,int y){
			cout<<"Drawing Circle[color:green,radius:"<<radius<<",x:"
				<<x<<",y:"<<y<<"]"<<endl;
		}
};

class Shape{
	public:
		virtual void draw()=0;
	protected:
		Shape(DrawAPI* drawAPI){
			this->drawAPI=drawAPI;
		}
	protected:
		DrawAPI* drawAPI;
};

class Circle:public Shape{
	public:
		Circle(int x,int y,int radius,DrawAPI* drawAPI):Shape(drawAPI){
			this->x=x;
			this->y=y;
			this->radius=radius;
			
		}

		void draw(){
			drawAPI->drawCircle(radius,x,y);
		}

	private:
		int x;
		int y;
		int radius;
};

int main()
{
	Shape* redCircle=new Circle(100,100,10,new RedCircle());
	Shape* greenCircle=new Circle(80,80,15,new GreenCircle());

	redCircle->draw();
	greenCircle->draw();

	return 0;
}

七、过滤器模式

#include<iostream>
#include<string>
#include<list>

using namespace std;

class Person{
    public:
        Person(string name,string gender,string maritalStatus)
        {
            this->name=name;
            this->gender=gender;
            this->maritalStatus=maritalStatus;
        }
        string getName(){return name;}
        string getGender(){return gender;}
        string getMaritalStatus(){return maritalStatus;}
    private:
        string name;
        string gender;
        string maritalStatus;
};

class Criteria{
    public:
        virtual list<Person*>* meetCriteria(list<Person*>* persons){};
};

class CriteriaMale:public Criteria{
    public:
        list<Person*>* meetCriteria(list<Person*>* persons){
            list<Person*> *malePersons = new list<Person*>;
            for(auto person:(*persons))
            {
                if(person->getGender()=="MALE"){
                    malePersons->push_back(person);
                }
            }
            return malePersons;
        }
};


class CriteriaFemale:public Criteria{
    public:
        list<Person*>* meetCriteria(list<Person*>* persons){
            list<Person*> *femalePersons = new list<Person*>;
            for(auto person:(*persons))
            {
                if(person->getGender()=="FEMALE"){
                    femalePersons->push_back(person);
                }
            }
            return femalePersons;
        }
};

class CriteriaSingle:public Criteria{
    public:
        list<Person*>* meetCriteria(list<Person*>* persons){
            list<Person*> *singlePersons = new list<Person*>;
            for(auto person:(*persons))
            {
                if(person->getMaritalStatus()=="SINGLE"){
                    singlePersons->push_back(person);
                }
            }
            return singlePersons;
        }
};


class AndCriteria:public Criteria{
    public:
        AndCriteria(Criteria *criteriaptr,Criteria* otherCriteriaptr){
            this->criteria=criteriaptr;
            this->othercriteria=otherCriteriaptr;
        }

        list<Person*>* meetCriteria(list<Person*>* persons){
            list<Person*>* firstCriteriaPersons=criteria->meetCriteria(persons);
            return othercriteria->meetCriteria(firstCriteriaPersons);
        }

    private:
        Criteria* criteria;
        Criteria* othercriteria;
};


class OrCriteria:public Criteria{
public:
    OrCriteria(Criteria *criteriaptr,Criteria* otherCriteriaptr){
        this->criteria=criteriaptr;
        this->othercriteria=otherCriteriaptr;

    }

    list<Person*>* meetCriteria(list<Person*>* persons){
        list<Person*>* firstCriteriaItems=criteria->meetCriteria(persons);
        list<Person*>* otherCriteriaItems=othercriteria->meetCriteria(persons);

        list<Person*>::iterator otherperson;
        list<Person*>::iterator firstPerson;

        for(otherperson=otherCriteriaItems->begin();otherperson!=otherCriteriaItems->end();otherperson++){
            for(firstPerson=firstCriteriaItems->begin();firstPerson!=firstCriteriaItems->end();firstPerson++){
                if((*otherperson)->getName() == (*firstPerson)->getName() &&
                    (*otherperson)->getGender() == (*firstPerson)->getGender() &&
                        (*otherperson)->getMaritalStatus() == (*firstPerson)->getMaritalStatus()) break;
            }
            if(firstPerson == (*firstCriteriaItems).end()){
                firstCriteriaItems->push_back(*otherperson);
            }
        }
        return firstCriteriaItems;
    }

八、组合模式

#include<iostream>
#include<string>
#include<list>
using namespace std;

class Employee{
    public:
        Employee(string nameparm, string deptparm,int salparm){
            this->name=nameparm;
            this->dept=deptparm;
            this->salary=salparm;
            if(subordinates==nullptr) subordinates=new list<Employee*>;
        }

        void add(Employee* e){
            subordinates->push_back(e);
        }

        void remove(Employee* e){
            delete e;
            subordinates->remove(e);
        }

        list<Employee*>* getSubordinates(){
            return subordinates;
        }

        string toString(){
            return "Employee:[Name:"+name+",dept:"+dept+ \
                ",salary:"+to_string(salary)+"]";
        }

    private:
        string name;
        string dept;
        int salary;
        list<Employee*>* subordinates{nullptr};
};


int main()
{
    Employee *CEO= new Employee("John","CEO",30000);

    Employee *headSales= new Employee("Robert","Head Sales",20000);

    Employee *headMarketing= new Employee("Michel","Head Marketing",20000);

    Employee *clerk1=new Employee("Laura","Marketing",10000);
    Employee *clerk2=new Employee("Bob","Marketing",10000);

    Employee *salesExecutive1=new Employee("Richard","Sales",10000);
    Employee *salesExecutive2=new Employee("Rob","Sales",10000);

    CEO->add(headSales);
    CEO->add(headMarketing);

    headSales->add(salesExecutive1);
    headSales->add(salesExecutive2);

    headMarketing->add(clerk1);
    headMarketing->add(clerk2);

    cout<<CEO->toString()<<endl;
    for(auto headEmployee:*CEO->getSubordinates()){
        cout<<headEmployee->toString()<<endl;
        for(auto employee:*headEmployee->getSubordinates()){
            cout<<employee->toString()<<endl;
        }
    }

    return 0;
}

九、装饰器模式

#include<iostream>
#include<string>
using namespace std;

class Shape{
	public:
		virtual void draw()=0;
};

class Rectangle:public Shape{
	public:
		void draw(){
			cout<<"Shape:Rectangle"<<endl;
		}
};


class Circle:public Shape{
	public:
		void draw(){
			cout<<"Shape:Circle"<<endl;
		}
};

class ShapeDecorator:public Shape{
	public:
		ShapeDecorator(Shape* decoratedShapeparm){
			this->decoratedShape=decoratedShapeparm;
		}

		void draw(){
			decoratedShape->draw();
		}
	protected:
		Shape* decoratedShape;
};

class RedShapeDecorator:public ShapeDecorator{
	public:
		using ShapeDecorator::ShapeDecorator;
		//RedShapeDecorator(Shape* decoratedShape):ShapeDecorator(decoratedShape){}

		void draw(){
			decoratedShape->draw();
			setRedBorder(decoratedShape);
		}

		void setRedBorder(Shape* decoratedShape){
			cout<<"Border Color:Red"<<endl;
		}
};

int main(){
	Shape *circle=new Circle();
	Shape *redCircle=new RedShapeDecorator(circle);
	Shape *redRectangle=new RedShapeDecorator(new Rectangle());
	
	cout<<"Circle with normal border"<<endl;
	circle->draw();

	cout<<"Circle of red border"<<endl;
	redCircle->draw();

	cout<<"Rectangle of red border"<<endl;
	redRectangle->draw();

	return 0;
}

十、外观模式

#include<iostream>
#include<string>
using namespace std;

class Shape{
	public:
		virtual void draw()=0;
};

class Rectangle:public Shape{
	public:
		void draw(){
			cout<<"Rectangle::draw()"<<endl;
		}
};

class Square:public Shape{
	public:
		void draw(){
			cout<<"Square::draw()"<<endl;
		}
};

class Circle:public Shape{
	public:
		void draw(){
			cout<<"Circle::draw()"<<endl;
		}
};

class ShapeMaker{
	public:
		ShapeMaker(){
			this->circle=new Circle();
			this->rectangle=new Rectangle();
			this->square=new Square();
		}

		void drawCircle(){
			circle->draw();
		}

		void drawRectangle(){
			rectangle->draw();
		}

		void drawSquare(){
			square->draw();
		}

	private:
		Shape* circle;
		Shape* rectangle;
		Shape* square;
};

int main()
{
	ShapeMaker *shapeMaker=new ShapeMaker();

	shapeMaker->drawCircle();
	shapeMaker->drawRectangle();
	shapeMaker->drawSquare();

	return 0;
}

十一、享元模式

#include<iostream>
#include<string>
#include<map>
#include<time.h>
#include<stdlib.h>
#include <stdexcept>
using namespace std;

class Shape{
    public:
        virtual void draw()=0;
};

class Circle:public Shape{
    public:
        Circle(string colorparm){
            this->color=colorparm;
        }

        void setX(int x){
            this->x=x;
        }

        void setY(int y){
            this->y=y;
        }

        void setRadius(int radius){
            this->radius=radius;
        }

        void draw(){
            cout<<"Circle:Draw() [Color:"<<color<<",x:"
                <<x<<",y:"<<y<<",radius:"<<radius<<"]"<<endl;
        }
    private:
        string color;
        int x;
        int y;
        int radius;
};

class ShapeFactory{
    public:
        ShapeFactory(){
            if(circleMap==nullptr) circleMap=new map<string,Shape*>;
        }

        Shape* getCircle(string color){
            Circle* circle=nullptr;
            try{
                circle=static_cast<Circle*>(circleMap->at(color));
            }
            catch (const std::out_of_range& oor) {
                cout<<color<<oor.what()<<" is failed"<<endl;
                circle=new Circle(color);
                circleMap->insert(make_pair(color,circle));
                cout<<"Creating circle of color:"<<color<<endl;
            }
            return circle;
        }
    private:
         map<string,Shape*>* circleMap{nullptr};
};

int getRandomX(){
    return rand()%30;
}

int getRandomY(){
    return rand()%30;
}

string getRandomColor(string colors[]){
    return colors[(int)rand()%5];
}

int main()
{
    string colors[]={"Red","Green","Blue","White","Black"};
    ShapeFactory shapefactory;
    srand((unsigned)time(NULL));

    for(int i=0;i<20;++i){
        Circle *circle=static_cast<Circle*>(shapefactory.getCircle(getRandomColor(colors)));
        circle->setX(getRandomX());
        circle->setY(getRandomY());
        circle->setRadius(100);
        circle->draw();
    }

    return 0;
}

十二、代理模式

#include<iostream>
#include<string>
using namespace std;

class Image{
	public:
		virtual void display()=0;
};

class RealImage:public Image{
	public:
		RealImage(string fileName){
			this->m_sfileName=fileName;
			loadFromDisk(m_sfileName);
		}

		void display()
		{
			cout<<"Displaying"<<m_sfileName<<endl;
		}

		void loadFromDisk(string fileName){
			cout<<"Loading"<<fileName<<endl;
		}
	private:
		string m_sfileName;
};

class ProxyImage:public Image{
	public:
		ProxyImage(string fileName){
			this->m_sfileName=fileName;
		}

		void display(){
			if(m_prealImage==nullptr)
			{
				m_prealImage=new RealImage(m_sfileName);
			}
			return m_prealImage->display();
		}
	private:
		RealImage* m_prealImage{nullptr};
		string m_sfileName;
};

int main()
{
	Image *image= new ProxyImage("test_10mb.jpg");
	image->display();  //图像将从磁盘加载

	image->display();   //图像不需要从磁盘加载
	
	return 0;
}

 

转载于:https://my.oschina.net/urlove/blog/2996894

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值