设计模式-桥接模式

桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立地变化

手机品牌与软件之间的联系 

package 设计模式;

public class Text {
	public static void main(String[] args) {
		 HandsetBrand ab;
		 ab=new HandsetBrandN();
		 ab.SetHandsetSoft(new HandsetGame());
		 ab.Run();
		 ab.SetHandsetSoft(new AddressList());
		 ab.Run();
		 ab=new HandsetBrandM();
		 ab.SetHandsetSoft(new HandsetGame());
		 ab.Run();
		 ab.SetHandsetSoft(new AddressList());
		 ab.Run();
		 ab.SetHandsetSoft(new Mp3());
	}
}
//手机软件
abstract class HandsetSoft
{
	public abstract void Run();
}
//手机品牌
abstract class HandsetBrand
{
	protected HandsetSoft soft;
	public void SetHandsetSoft(HandsetSoft soft)
	{
		this.soft=soft;
	}
	public abstract void Run();
}
class HandsetBrandM extends HandsetBrand
{
	public void Run()
	{
		System.out.println("M Brand");
		soft.Run();
	}
}
class HandsetBrandN extends HandsetBrand
{
	public void Run()
	{
		System.out.println("N Brand");
		soft.Run();
	}
}
class HandsetGame extends HandsetSoft
{
	public void Run()
	{
		System.out.println("运行手机游戏");
	}
}
class AddressList extends HandsetSoft
{
	public void Run()
	{
		System.out.println("运行手机通讯录");
	}
}
class Mp3 extends HandsetSoft
{
	public  void Run()
	{
		System.out.println("运行手机MP3");
	}
}

 

基本代码实现

 

package 设计模式;

public class Text {
	public static void main(String[] args) {
		Abstraction ab=new RefinedAbstraction();
		ab.SetImplementor(new ConcreteImplementorA());
		ab.Operation();
		ab.SetImplementor(new ConcreteImplementorB());
		ab.Operation();
	}
}
abstract class Implementor
{
	public abstract void Operation();
}
class ConcreteImplementorA extends Implementor
{
	public void Operation()
	{
		System.out.println("具体实现A的方法执行");
	}
}
class ConcreteImplementorB extends Implementor
{
	public void Operation()
	{
		System.out.println("具体实现B的方法执行");
	}
}
class Abstraction
{
	protected Implementor implementor;
	public void SetImplementor(Implementor implementor)
	{
		this.implementor=implementor;
	}
	public void Operation()
	{
		implementor.Operation();
	}
}
class RefinedAbstraction extends Abstraction
{
	public void Operation()
	{
		implementor.Operation();
	}
}

说明 

  •  桥接模式就是将抽象部分与它的实现部分分离,即实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让他们独立变化,减少它们之间的耦合
  • 桥接模式中的桥接是单向的,即只能是抽象部分的对象去使用具体实现部分的对象,而不能反过来
  • 使用桥接模式和原始解决方案的根本区别是通过继承还是通过合成/聚合方式去实现一个功能需求

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值