日期:2014-05-20  浏览次数:20692 次

用装饰者模式设计按钮样式
怎么用JAVA的装饰者模式 设计一个按钮  
如:用装饰者 改变一个按钮上的字体颜色和按钮的样式

刚学 不怎么懂 希望各位前辈 给下源码

谢谢了!

------解决方案--------------------
写了个例子,你比对着自己写吧。
Java code

//按钮接口
public interface Button {
    public void color();
    public void style();
}

//默认button
public 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();
    }
}