zoukankan      html  css  js  c++  java
  • 桥接模式-Bridge(Java实现)

    桥接模式-Bridge

    桥梁模式的用意是"将抽象化(Abstraction)与实现化(Implementation)脱耦, 将"类的功能层次结构" 与 "类的实现层次结构"分离为两个独立的类层次结构.

    类的实现层次接口

    DisplayImpl接口

    public interface DisplayImpl {
        void rawOpen();
    
        void rawPrint();
    
        void rawClose();
    }

    StringDisplayImpl类

    public class StringDisplayImpl implements DisplayImpl {
        private String string;
        private int width;
    
        public StringDisplayImpl(String string) {
            this.string = string;
            this.width = string.getBytes().length;
        }
    
        public void rawOpen() {
            printLine();
        }
    
        public void rawPrint() {
            System.out.println("|" + string + "|");
        }
    
        public void rawClose() {
            printLine();
        }
    
        private void printLine() {
            System.out.print("+");
            for (int i = 0; i < width; i++) {
                System.out.print("-");
            }
            System.out.println("+");
        }
    }

    类的功能层次结构

    Display类

    在功能实现的最高层上关联了DisplayImpl接口, 在此处进行了桥接.

    public class Display {
        private DisplayImpl impl;
    
        public Display(DisplayImpl impl) {
            this.impl = impl;
        }
    
        public void open() {
            impl.rawOpen();
        }
    
        public void print() {
            impl.rawPrint();
        }
    
        public void close() {
            impl.rawClose();
        }
    
        public final void display() {
            open();
            print();
            close();
        }
    }

    CountDisplay类

    在Display类的基础上, 进行功能上的扩展. 扩展一个multiDisplay()功能.

    public class CountDisplay extends Display {
        public CountDisplay(DisplayImpl impl) {
            super(impl);
        }
    
        public void multiDisplay(int times) {
            open();
            for (int i = 0; i < times; i++) {
                print();
            }
            close();
        }
    }

    Main

    用于测试运行

    public class Main {
        public static void main(String[] args) {
            Display d1 = new Display(new StringDisplayImpl("Hello, China."));
            Display d2 = new CountDisplay(new StringDisplayImpl("Hello, World."));
            CountDisplay d3 = new CountDisplay(new StringDisplayImpl("Hello, Universe."));
            d1.display();
            d2.display();
            d3.display();
            d3.multiDisplay(5);
        }
    }
    

  • 相关阅读:
    Oracle调优总结--(经典实践 重要)
    ORACLE索引介绍和使用
    ORACLE索引介绍和使用
    oracle update 改为 merge
    oracle update 改为 merge
    在 Eclipse 下利用 gradle 构建系统
    在 Eclipse 下利用 gradle 构建系统
    关于SQL查询效率,100w数据,查询只要1秒
    关于SQL查询效率,100w数据,查询只要1秒
    Add Binary
  • 原文地址:https://www.cnblogs.com/noKing/p/9010888.html
Copyright © 2011-2022 走看看