码迷,mamicode.com
首页 > 其他好文 > 详细

十二、Decorator 装饰器模式

时间:2019-03-05 14:10:03      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:height   bst   pen   make   div   color   lin   图片   his   

设计:

技术图片

代码清单:

Display

public abstract class Display {
    public abstract int getColumns();
    public abstract int getRows();
    public abstract String getRowText(int row);
    public final void show(){
        for(int i=0;i<getRows();i++){
            System.out.println(getRowText(i));
        }
    }
}

StringDisolay

public class StringDisplay extends Display{
    private String string;
    public StringDisplay(String string){
        this.string = string;
    }
    @Override
    public int getColumns() {
        return string.getBytes().length;
    }

    @Override
    public int getRows() {
        return 1;
    }

    @Override
    public String getRowText(int row) {
        if(row == 0){
            return string;
        }else{
            return null;
        }
    }
}

Border

public abstract class Border extends Display{
    protected  Display display;
    protected  Border(Display display){
        this.display = display;
    }
}

FullBorder

public class FullBorder extends Border{
    public FullBorder(Display display){
        super(display);
    }

    @Override
    public int getColumns() {
        return 1+display.getColumns()+1;
    }

    @Override
    public int getRows() {
        return 1+display.getRows()+1;
    }

    @Override
    public String getRowText(int row) {
        if(row ==0){
            return "+"+makeLine(-,display.getColumns())+"+";
        }else if(row ==display.getRows()+1){
            return  "+"+makeLine(-,display.getColumns())+"+";
        }else{
            return "|"+display.getRowText(row-1)+"|";
        }
    }

    private String makeLine(char ch,int count){
        StringBuffer buf = new StringBuffer();
        for(int i=0;i<count;i++){
            buf.append(ch);
        }
        return buf.toString();
    }
}

SideBorder

public class SideBorder extends Border{
    private char borderChar;
    public SideBorder(Display display,char ch){
        super(display);
        this.borderChar = ch;
    }
    @Override
    public int getColumns() {
        return 1 + display.getColumns() + 1;
    }

    @Override
    public int getRows() {
        return display.getRows();
    }

    @Override
    public String getRowText(int row) {
        return borderChar+display.getRowText(row)+borderChar;
    }
}

 

十二、Decorator 装饰器模式

标签:height   bst   pen   make   div   color   lin   图片   his   

原文地址:https://www.cnblogs.com/baizhuang/p/10476249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!