• 设计模式之装饰模式


    概述 

     JAVA23种设计模式之一,英文叫Decorator Pattern,又叫装饰者模式。装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

    装饰模式的特点

      (1) 装饰对象和真实对象有相同的接口。这样客户端对象就可以和真实对象相同的方式和装饰对象交互。
      (2) 装饰对象包含一个真实对象的索引(reference)
      (3) 装饰对象接受所有的来自客户端的请求。它把这些请求转发给真实的对象。

      (4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。

                       在面向对象的设计中,通常  是通过继承来实现对给定类的功能扩展。

    Java 实现代码

    package com.picc.cl;
    
    /**定义一个接口*/
    public interface Decorator {
    
    	String sayHi();
    
    }
    /**子类去实现这个接口*/
    class DecoratorA implements Decorator{
    
    	public String sayHi() {
    	 return "DecoratorA sayHi()";
    		
    	}
    	
    }
    /**子类去实现这个接口 并把这个接口类做为一个成员变量传入*/
    class DecoratorImpl implements Decorator {
    	private Decorator decorator;
    
    	public DecoratorImpl(Decorator decorator) {
    		this.decorator = decorator;
    	}
    
    	public String sayHi() {
    		 return "hello "+decorator.sayHi();
    	}
    }
    public class DecoratorTest {
    	public static void main(String[] args) {
    		DecoratorA decorator = new DecoratorA();
    		System.out.println(decorator.sayHi());
    		DecoratorImpl aDecoratorImpl = new DecoratorImpl(decorator);
    		System.out.println(aDecoratorImpl.sayHi());
    	}
    }
    

    运算结果
    DecoratorA sayHi()
    hello DecoratorA sayHi()

  • 相关阅读:
    PAT (Advanced Level) 1080. Graduate Admission (30)
    PAT (Advanced Level) 1079. Total Sales of Supply Chain (25)
    PAT (Advanced Level) 1078. Hashing (25)
    PAT (Advanced Level) 1077. Kuchiguse (20)
    PAT (Advanced Level) 1076. Forwards on Weibo (30)
    PAT (Advanced Level) 1075. PAT Judge (25)
    PAT (Advanced Level) 1074. Reversing Linked List (25)
    PAT (Advanced Level) 1073. Scientific Notation (20)
    PAT (Advanced Level) 1072. Gas Station (30)
    PAT (Advanced Level) 1071. Speech Patterns (25)
  • 原文地址:https://www.cnblogs.com/java20130726/p/3218306.html
Copyright © 2020-2023  润新知