• 桥接模式


    个人博客

    http://www.milovetingting.cn

    桥接模式

    模式介绍

    桥接模式也称为桥梁模式,是结构型设计模式之一。

    模式定义

    将抽象部分与实现部分分离,使它们都可以独立地进行变化。

    使用场景

    1. 一个系统需要在构件的抽象化角色和具体角色之间增加更多灵活性,避免在两个层次之间建立静态的继承关系,可以通过桥接模式使它们在抽象层建立一个关联关系。

    2. 不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统。

    3. 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

    简单使用

    定义抽象类

    public abstract class CoffeeAdditives {
    	public abstract String addSomething();
    }
    

    定义实现类

    public class Sugar extends CoffeeAdditives {
    
    	@Override
    	public String addSomething() {
    		return "加糖";
    	}
    
    }
    
    public class Ordinary extends CoffeeAdditives{
    
    	@Override
    	public String addSomething() {
    		return "原味";
    	}
    
    }
    

    定义抽象类

    public abstract class Coffee {
    
    	protected CoffeeAdditives coffeeAdditives;
    
    	public Coffee(CoffeeAdditives coffeeAdditives) {
    		super();
    		this.coffeeAdditives = coffeeAdditives;
    	}
    
    	public abstract void makeCoffee();
    
    }
    

    定义实现类

    public class LargeCoffee extends Coffee {
    
    	public LargeCoffee(CoffeeAdditives coffeeAdditives) {
    		super(coffeeAdditives);
    	}
    
    	@Override
    	public void makeCoffee() {
    		System.out.println("大杯的" + coffeeAdditives.addSomething() + "咖啡");
    	}
    
    }
    
    public class SmallCoffee extends Coffee {
    
    	public SmallCoffee(CoffeeAdditives coffeeAdditives) {
    		super(coffeeAdditives);
    	}
    
    	@Override
    	public void makeCoffee() {
    		System.out.println("小杯的" + coffeeAdditives.addSomething() + "咖啡");
    	}
    
    }
    

    调用

    public class Main {
    
    	public static void main(String[] args) {
    		Ordinary ordinary = new Ordinary();
    
    		Sugar sugar = new Sugar();
    
    		LargeCoffee largeCoffee = new LargeCoffee(ordinary);
    		largeCoffee.makeCoffee();
    
    		SmallCoffee smallCoffee = new SmallCoffee(ordinary);
    		smallCoffee.makeCoffee();
    
    		LargeCoffee largeCoffee2 = new LargeCoffee(sugar);
    		largeCoffee2.makeCoffee();
    
    		SmallCoffee smallCoffee2 = new SmallCoffee(sugar);
    		smallCoffee2.makeCoffee();
    
    	}
    
    }
    

    输出结果

    大杯的原味咖啡
    小杯的原味咖啡
    大杯的加糖咖啡
    小杯的加糖咖啡
    
  • 相关阅读:
    数据库设计三大范式
    MySQL笔试题搜罗
    [转载]MySql事物处理
    网页错误代码大全
    【转载】linux环境下大数据网站搬家
    Linux常用命令
    MongoDB概述
    Linux系统下通过命令行对mysql数据进行备份和还原
    wamp提示:与服务器的连接断开,请检查网络状况与服务器的运行状态的解决方法
    HDU 4578 线段树各种区间操作
  • 原文地址:https://www.cnblogs.com/milovetingting/p/12329534.html
Copyright © 2020-2023  润新知