加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

大话设计模式二十二:桥接模式(手机软件何时统一)

发布时间:2020-12-13 19:41:40 所属栏目:百科 来源:网络整理
导读:桥接模式: 当发现我们需要多角度去分类实现对象,而只用继承会造成大量的类增加,不能满足开放-封闭 原则,就应该考虑用桥接模式了。 // 手机接口public abstract class Mobile {private MobileSoft soft;private String brand;public Mobile(String brand)

桥接模式:

当发现我们需要多角度去分类实现对象,而只用继承会造成大量的类增加,不能满足开放-封闭 原则,就应该考虑用桥接模式了。

// 手机接口
public abstract class Mobile {

	private MobileSoft soft;
	private String brand;

	public Mobile(String brand) {
		this.brand = brand;
	}

	public MobileSoft getSoft() {
		return soft;
	}

	public void setSoft(MobileSoft soft) {
		this.soft = soft;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public abstract void run();
}

// nokia手机
public class NokiaMobile extends Mobile {

	public NokiaMobile(String brand) {
		super(brand);
	}

	@Override
	public void run() {
		System.out.print("Nokia Mobile: ");
		this.getSoft().run();
	}

}


// moto手机
public class MotoMible extends Mobile {

	public MotoMible(String brand) {
		super(brand);
	}

	@Override
	public void run() {
		System.out.print("Moto Mobile: ");
		this.getSoft().run();
	}

}


// 手机软件
public abstract class MobileSoft {
	
	public abstract void run();
	
}

// 手机软件: mp3播放器
public class MobileMp3 extends MobileSoft {

	@Override
	public void run() {
		System.out.println("run mobile mp3!");
	}

}

// 手机软件: 游戏
public class MobileGame extends MobileSoft {

	@Override
	public void run() {
		System.out.println("run mobile game!");
	}

}

public class BridgeMain {

	public static void main(String[] args) {
		Mobile nokia = new NokiaMobile("Nokia");
		MobileSoft game = new MobileGame();
		nokia.setSoft(game);
		nokia.run();

		Mobile moto = new MotoMible("Moto");
		MobileSoft mp3 = new MobileMp3();
		moto.setSoft(mp3);
		moto.run();
	}

}

合成/聚合复用原则:

聚合表示一种弱的拥有关系,体现的是A对象可以包含B对象,但B对象不是A对象的一部分(大雁和雁群是聚合关系)。

合成表示一种强的拥有关系,体现了严格的部分和整体的关系,部分和整体的生命周期一样(大雁和翅膀就是合成关系)。

合成/聚合复用原则优点:

优先使用对象的合成/聚合将有助于你保持每个类被封装,这样类和类继承层次会保持较小规模,并且不太可能增长为不可控制的庞然大物。

为什么不用继承?

继承是一种强耦合的关系,父类变,子类也得跟着变,所以我们在用继承时,一定要在是‘is a’ 的关系时再考虑使用。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读