十Decorator 装饰器模式
Posted baizhuang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了十Decorator 装饰器模式相关的知识,希望对你有一定的参考价值。
设计:
代码清单:
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 装饰器模式的主要内容,如果未能解决你的问题,请参考以下文章