zoukankan      html  css  js  c++  java
  • 设计模式一桥接模式

    概述

    是针对同一接口进行扩展与实现操作的一种设计模式。

    把抽象类或者接口的具体实现和扩展分开来以达到扩展功能不影响实现,增加实现又不影响扩展的功能,

    在抽象层对两者做组合关联,是用组合的方式来解决继承的问题。

    桥接模式和适配器模式的区别:

    1. 首先是两者的目的不同,桥接是为了分离接口的功能扩展和抽象方法的实现,而适配器模式是为了对同一实现提供不同接口。
    2. 其次是二者的实现方式不同,桥接是利用新接口去继承原先的旧接口,以此来提供新的接口给新的实现类,而桥接并不是为了改变接口,而是去为原来的接口增加功能。

    抽象化(Abstraction)角色:

      定义抽象类,并包含一个对实现化对象的引用。
    扩展抽象化(Refined Abstraction)角色:
      是抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色中的业务方法。
    实现化(Implementor)角色:
      定义实现化角色的接口,供扩展抽象化角色调用。
    具体实现化(Concrete Implementor)角色:
      给出实现化角色接口的具体实现。
     1 public class Bridge {
     2     public static void main(String[] args) {
     3         fruit fruit = new fruit(new red());
     4         fruit.eat();
     5         fruit.color.theColor();
     6     }
     7 }
     8 
     9 //接口
    10 interface color {
    11     void theColor();
    12 }
    13 
    14 class blue implements color {
    15     @Override
    16     public void theColor() {
    17         System.out.println("这是blue");
    18     }
    19 }
    20 
    21 class red implements color {
    22     @Override
    23     public void theColor() {
    24         System.out.println("这是red");
    25     }
    26 }
    27 
    28 //抽象
    29 abstract class food {
    30     //实现部分角色,使用组合实现桥接
    31     protected color color;
    32 
    33     //桥接模式的关键,组合实现和抽象
    34     public food(color color) {
    35         this.color = color;
    36     }
    37 
    38     public abstract void eat();
    39 }
    40 
    41 class meat extends food {
    42     public meat(color color) {
    43         super(color);
    44     }
    45 
    46     @Override
    47     public void eat() {
    48         System.out.println("吃肉");
    49     }
    50 }
    51 
    52 class fruit extends food {
    53 
    54     public fruit(color color) {
    55         super(color);
    56     }
    57 
    58     @Override
    59     public void eat() {
    60         System.out.println("吃水果");
    61     }
    62 }
  • 相关阅读:
    laravel路由和MVC
    laravel目录介绍
    laravel下载安装
    Mac 程序员的十种武器
    Python中列表的copy方法
    Ubuntu 安装vim失败解决
    Linux userAdd 增加用户如果没有配置文件情况解决
    Ubuntu 软件管理
    awk工具详解
    httpsClient
  • 原文地址:https://www.cnblogs.com/loveer/p/11273332.html
Copyright © 2011-2022 走看看