现在的位置: 首页 > 综合 > 正文

设计模式-结构型模式-桥接

2017年12月08日 ⁄ 综合 ⁄ 共 2181字 ⁄ 字号 评论关闭

结构型模式:结构型对象模式不是对接口或实现进行组合的.而是描述了如何对一些对象进行组合,从而实现新功能的一些方法.

bridge模式:将抽像部份与它的实现部份分离,使它们多可以独立变化.

       适用性:你不希望在抽象与实现之间有一个固定的绑定关系.

 

package structure.brigde;
/**
 *  A test client
 */
public class Test  {
    public Test() {
    }

    public static void main(String[] args) {
        Text myText = new TextBold("Mac");
        myText.DrawText("=== A test String ===");

        myText =  new TextBold("Linux");
        myText.DrawText("=== A test String ===");

        System.out.println("------------------------------------------");
       
        myText =  new TextItalic("Mac");
        myText.DrawText("=== A test String ===");

        myText =  new TextItalic("Linux");
        myText.DrawText("=== A test String ===");       
    }
}

 

package structure.brigde;
/**
 *  The Abstract of Text
 */
public abstract class Text  {
    public abstract void DrawText(String text);
    protected TextImp GetTextImp(String type) {
        if(type.equals("Mac")) {
            return new TextImpMac();
        } else if(type.equals("Linux")) {
            return new TextImpLinux();
        } else {
            return new TextImpMac();
        }
    }
}

 

package structure.brigde;
/**

 *  The RefinedAbstraction
 */
import java.io.*;

public class TextBold extends Text {
    private TextImp imp;
    public TextBold(String type) {
        imp = GetTextImp(type);
    }
    public void DrawText(String text) {
        System.out.println(text);
        System.out.println("The text is bold text!");
        imp.DrawTextImp();
    }
}

 

package structure.brigde;
/**
 *  The Implementor
 */
public interface TextImp  {
    public abstract void DrawTextImp();
}

 

package structure.brigde;
/**
 *  The ConcreteImplementor
 */
public class TextImpLinux implements TextImp {
    public TextImpLinux() {
    }
    public void DrawTextImp() {
        System.out.println("The text has a Linux style !");
    }
}

 

package structure.brigde;
/**
 *  The ConcreteImplementor
 */
public class TextImpMac implements TextImp {
    public TextImpMac() {
    }
    public void DrawTextImp() {
        System.out.println("The text has a Mac style !");
    }
}

 

package structure.brigde;
/**
 *  The RefinedAbstraction
 */
public class TextItalic extends Text {
    private TextImp imp;
    public TextItalic(String type) {
        imp = GetTextImp(type);
    }
    public void DrawText(String text) {
        System.out.println(text);
        System.out.println("The text is italic text!");
        imp.DrawTextImp();
    }
}

抱歉!评论已关闭.