设计模式java——桥接模式

本文通过一个具体的示例详细介绍了桥接模式的应用。该模式通过将抽象与其实现解耦,使得两者可以独立变化。示例中包括了不同类型的水果(如苹果和柠檬)以及不同的销售场所(如超市和小商店),展示了如何根据不同场景调整价格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

桥接模式Demo:

/**
 * 2018年4月5日下午9:32:03
 */
package com.Designpattern;

/**
 * @author xinwenfeng
 *
 */
public class TestBridge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Shop supermarket = new Supermarket();
		Shop smallshop = new SmallShop();
		Fruit apple = new Apple();
		Fruit lemon = new Lemon();
		supermarket.setFruit(apple);
		supermarket.sellFruit();
		supermarket.setFruit(lemon);
		supermarket.sellFruit();
		System.out.println("=======================");
		smallshop.setFruit(apple);
		smallshop.sellFruit();
		smallshop.setFruit(lemon);
		smallshop.sellFruit();
	}

}
interface Fruit{
	String getName();
	float getPrice();
}
class Apple implements Fruit{
	
	public String getName() {
		return "苹果";
	}
	
	@Override
	public float getPrice() {
		return 4.4f;
	}
	
}
class Lemon implements Fruit{

	public String getName() {
		return "柠檬";
	}
	
	@Override
	public float getPrice() {
		return 6.6f;
	}
	
}
abstract class Shop{
	protected Fruit fruit;
	public void setFruit(Fruit f) {
		fruit = f;
	}
	abstract void sellFruit();
}
class Supermarket extends Shop{

	@Override
	void sellFruit() {
		float price = fruit.getPrice() * 1.2f;
		System.out.println("超市的"+fruit.getName()+"单价(元):"+price);
	}
	
}
class SmallShop extends Shop{

	@Override
	void sellFruit() {
		float price = fruit.getPrice() * 1.3f;
		System.out.println("小商店的"+fruit.getName()+"单价(元):"+price);
	}
	
}

结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值