zoukankan      html  css  js  c++  java
  • 设计模式3:装饰模式

    这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

    意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。

    主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。

    为了避免子类数量的快速膨胀,我们可以用装饰模式为对象动态的增加功能。

    这些功能应该是没有相互关联和先后顺序的。

    举例来说,一个人可以穿各种不同的装扮,如果为每套打扮生成一个子类,那么子类的数量将爆炸。

    可以将装饰模式应用进来,使用衣物装饰人。

    来看UML图:

    Component类是公共基类,定义了show方法。

    Person类继承Component类,实现show方法。

    Cloth对象将Component类作为其实例变量。

    Trouser和TShirts类实现了show方法。

    来看具体代码:

    public abstract class Component {
    	public abstract void show();
    }
    

    Component定义一个虚方法。

    public class Person extends Component {
    	
    	private String name = null;
    
    	public Person(String name) {
    		this.name = name;
    	}
    	
    	public void show() {
    		System.out.println("我是" + name);
    	}
    }
    

    Person实现了这个虚方法。

    public class Cloth extends Component {
    	
    	protected Component component = null;
    
    	public Cloth(pers.zcy.decorator.Component component) {
    		super();
    		this.component = component;
    	}
    
    	@Override
    	public void show() {
    		if(component != null){
    			component.show();
    		}
    	}
    
    }
    

    Cloth类是装饰器的基类,其中包含一个Component实例对象,在show中调用这个实例对象的show方法。

    public class Trouser extends Cloth {
    
    	public Trouser(Component component) {
    		super(component);
    		// TODO Auto-generated constructor stub
    	}
    	
    	@Override
    	public void show(){
    		super.show();
    		System.out.println("我穿了裤子");
    	}
    }
    
    public class TShirts extends Cloth {
    
    	public TShirts(Component component) {
    		super(component);
    	}
    
    	@Override
    	public void show(){
    		super.show();
    		System.out.println("我穿了T恤");
    	}
    }
    

    这两个类重写show方法,同时显式调用父类方法。

    public class DecoratorDemo {
    	public static void main(String[] args) {
    		Person person = new Person("Mike");
    		Cloth tshirts = new TShirts(person);
    		Cloth trousers = new Trouser(tshirts);
    		trousers.show();
    	}
    }
    

      

  • 相关阅读:
    招聘ASP.NET(C#)开发人员(已经截止,谢谢大家支持)
    VisualStudioCode开发Vue
    全局异常处理机制(Filter拦截器对比)
    工程师
    kubernetes(k8s)里面部署服务器集群并访问项目
    webpack 就是前端模块化打包工具
    Visual Studio Code配置C/C++开发环境
    docker和k8s(Kubernetes)是配套使用
    kettle 多表全删全插同步数据
    wireshark 抓HTTPS 的包 HTTPS = TLS + HTTP TLSv1.2 协议
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6670652.html
Copyright © 2011-2022 走看看