1.Java设计模式-->装饰者模式

 作为一个Java小白,面向对象编程的几个特性:封装\继承\多态,我一直真正了解的不多.这个模式却让我一下理解了多态的好处:它可以很方便的对系统进行解耦.废话不讲,上代码和注释
 
1.公共接口

public interface Appearance{
    void draw();
}

2.基本实现类和一个用作装饰别的Appearance子类的抽象类

//这里列出来两个基本实现类
public class Circle implements Appearance{

    @override
    public void draw(){
      System.out.println("画个圆形");
    }
}

public class Rectangle implements Appearance{

    @override
    public void draw(){
      System.out.println("画个矩形");
}
//一个装饰Appearance子类的抽象类
public abstract class AppearanceDecorator implements Appearance{

    //声明为proteced可以被子类继承
    protected Appearance decoratedAppearance;

    public AppearanceDecorator(Appearance decoratedAppearance){
      this.decoratedAppearance = decoratedrAppearance;
    }

    @override
    public void draw(){
      decoratedAppearance.draw();
    }
}

3.装饰的具体实现类

public class RedAppearanceDecorator extends AppearanceDecorator{

    public RedAppearanceDecorator(Appearance decoratedAppearance){
      super(decoratedAppearance);
    }

    private void setRedBorder(){
      System.out.println("进行镶边");
      System.out.println("done!红色镶边");
    }

    @override
    public void draw(){
      decoratedAppearance.draw();
      setRedBorder();
    }
}

接下来:用测试类来测试一下即可:

public class Test{
    public static void(String[] args){
      Appearance circle = new Circle();
      circle.draw();

      Appearance rectangle = new Rectangle();
      rectangle.draw();

      Appearance redCircle = new RedAppearanceDecorator( new Circle() );
      redCircle.draw();
    }
}

最后,简单一提,学习设计模式一方面是要加深对java体系的理解,另一方面也是增长自己的设计能力.
在Java的io操作中,
BufferedWirter \ OutputStreamWriter 是Writer的子类
其中BufferedWriter就是具体的装饰类.以后,会结合具体的Java或者Andoid源代码进行讲解.
源代码我现在阅读起来还有些费力气,但是最起码要有读源代码的意识,这是开发者必备的技能.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值