昨天看完毕老师的IO流章视频教程,颇有感触,老师在讲到BufferedReader中readerLine方法时说到,其本质上是read方法的一个增强,采用是的Dercorator设计模式,额外的为类添加职责行为,该设计模式利用多态思想,实现了高内聚,低耦合,提高了程序的复用性和健壮性。以后诸多常用类均有使用 ,我就试着写了比较简单java版Decorator设计模式样本,分享一下 。好了 废话不多说,上代码!- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package javaapplication10;
- /*
- *
- * @author Any
- */
- public class Main {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args)
- {
- // TODO code application logic here
- Component _com=new ConcreteComponent();
- Decorator _dec=new ConcreteDecorator(_com);
- _dec.Operation();
-
- }
- }
- //定义一个抽象基类,实现多态
- abstract class Component {
- protected Component(){}
- public abstract void Operation();
- }
- class ConcreteComponent extends Component{
- public ConcreteComponent(){};
- public void Operation(){
- System.out.println("ConcreteComponent::Operation");
- }
- }
- class Decorator extends Component{
- protected Component _com;
- public Decorator(){};
- public Decorator(Component _com){
- this._com=_com;
- }
- public void Operation(){
- System.out.println("Decorator::Operation");
- }
- }
- class ConcreteDecorator extends Decorator{
- public ConcreteDecorator(Component _com){
- super(_com);
- }
- //Override
- <font color="#ff0000">//将增强职责部分添加此处,以便于实现增强功能</font>
- public void Operation(){
- _com.Operation();
- this.AddBehavior();
- }
- <font color="#ff0000">//这就是要增强职责行为部分,可自行添加想要实现的职责行为</font>
- public void AddBehavior(){
- System.out.println("ConcreteDecorator::AddBehavior");
- }
- }
复制代码 |