桥接模式(Bridge):将抽象部分与它的实现部分分离,使它们均可以独立地变化。java
桥接模式Demo:app
/** * 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); } }
结果:ide