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;
    }

    执行: 



  • 相关阅读:
    java当前时间
    @Repository、@Service、@Controller 和 @Component
    spring mvc controller间跳转 重定向 传参
    MVC思想
    AJAX
    MySQL优化大总结
    MySQL数据库优化
    java JDBM2 的几个简单实例
    集群环境下如何防止定时任务重复执行?
    Java应用集群下的定时任务处理方案(mysql)
  • 原文地址:https://www.cnblogs.com/mthoutai/p/6740885.html
Copyright © 2011-2022 走看看