怎么用JAVA的装饰者模式 设计一个按钮
如:用装饰者 改变一个按钮上的字体颜色和按钮的样式
刚学 不怎么懂 希望各位前辈 给下源码
谢谢了!
------解决方案--------------------------------------------------------
写了个例子,你比对着自己写吧。
- Java code
//按钮接口public interface Button { public void color(); public void style();}//默认buttonpublic class DefaultButton implements Button { private String color = "default"; private String style = "default sytle"; protected String getColor() { return color; } protected void setColor(String color) { this.color = color; } protected String getStyle() { return style; } protected void setStyle(String style) { this.style = style; } @Override public void color() { System.out.println("button color is " + getColor()); } @Override public void style() { System.out.println("button style is " + getStyle()); }}//红色按钮public class RedButton implements Button{ private String color = "red"; private String style = "red sytle"; private DefaultButton db; public RedButton(DefaultButton db){ this.db = db; db.setColor(color); db.setStyle(style); } @Override public void color() { db.color(); } @Override public void style() { db.style(); } protected String getColor() { return color; } protected void setColor(String color) { this.color = color; } protected String getStyle() { return style; } protected void setStyle(String style) { this.style = style; }}//测试类public class Test{ public static void main(String[] args) { RedButton rb = new RedButton(new DefaultButton()); rb.color(); rb.style(); }}