zoukankan      html  css  js  c++  java
  • Design Pattern Bridge 桥设计模式

    桥设计模式事实上就是一个简单的has a relationship。就是一个类拥有还有一个类,并使用还有一个类实现须要的功能。

    比方遥控器和电视之间能够使用桥设计模式达到能够使用同一个遥控器控制多台电视机的目的。

    这种设计思想是多种设计模式反重复复使用基本思想。

    细致思考下会发现多种设计模式的底层思想事实上是相通的。只是详细实现或者某些细节。应用等有那么一点区别罢了。

    以下就实现一个TV和remoter类,当中的remoter是能够随时更换的。

    #include <stdio.h>
    
    class Remoter
    {
    public:
    	virtual void changeChannel() = 0;
    };
    
    class OldRemoter : public Remoter
    {
    	short channel;
    public:
    	OldRemoter(short c) : channel(c) {}
    	void changeChannel()
    	{
    		printf("Channel : %d
    ", channel++);
    	}
    };
    
    class NewRemoter : public Remoter
    {
    	int channel;
    public:
    	NewRemoter(int c) : channel(c) {}
    	void changeChannel()
    	{
    		printf("Channel : %d
    ", channel++);
    	}
    };
    
    class TV
    {
    protected:
    	Remoter *remoter;
    	int channel;
    public:
    	TV(Remoter *r) : remoter(r), channel(0) {}
    	virtual void changeRemoter(Remoter *r)
    	{
    		remoter = r;
    	}
    
    	virtual void changeChannel()
    	{
    		remoter->changeChannel();
    	}
    };
    
    class BrandOneTV : public TV
    {
    public:
    	BrandOneTV(Remoter *r) : TV(r){}
    };
    
    int main()
    {
    	Remoter *ore = new OldRemoter(0);
    	Remoter *nre = new NewRemoter(1);
    
    	TV *tv1 = new BrandOneTV(ore);
    	tv1->changeChannel();
    	ore->changeChannel();
    	tv1->changeChannel();
    
    	tv1->changeRemoter(nre);
    	tv1->changeChannel();
    	nre->changeChannel();
    	tv1->changeChannel();
    
    	return 0;
    }

    执行: 



  • 相关阅读:
    人月神教α阶段冲刺报告(6/12)
    人月神教α阶段冲刺报告(5/12)
    人月神教-α阶段冲刺报告(4/12)
    人月神教-α阶段冲刺报告(3/12)
    结对作业2
    结对作业1
    软工实践作业1
    Matrix Power Series(POJ 3233)
    Blocks(POJ 3734)
    Traveling by Stagecoach(POJ 2686)
  • 原文地址:https://www.cnblogs.com/mthoutai/p/6740885.html
Copyright © 2011-2022 走看看