java装饰模式代码实现

1、父类 person 包含唯一公有属性

2、服饰类继承Finery继承共有类 并重写父类方法 添加自己的构造方法,和重写show()方法(装饰模式的核心) 

3、//具体服饰类TShirts ,Kuzi, Overcoat继承了 服饰类Finery并且重写show的方法添加自己的功能

使用过程:

public class Decoraror_Model02_plus {
  public static void main(String[] args) {
	  Person jun=new Person("jun");
	  TShirts Ts=new  TShirts();
	  Kuzi Kz=new Kuzi();
	  Overcoat Oc=new Overcoat();
	  //注意顺序 顺序不能返 否则空指针
		 Ts.Decorate(jun);	    //穿上Ts	
		 Kz.Decorate(Ts);	    //穿上Kz
		 Oc.Decorate(Kz);      //穿上Oc
		 Oc.show();
		
}
}

 

package ch6_DecoratorModel;

/**
 * 
 * 		具体事项装饰模式  相比上一个去掉Component类
 * @author Administrator
 *		
 */
public class Decoraror_Model02_plus {
  public static void main(String[] args) {
	  Person jun=new Person("jun");
	  TShirts Ts=new  TShirts();
	  Kuzi Kz=new Kuzi();
	  Overcoat Oc=new Overcoat();
	  //注意顺序 顺序不能返 否则空指针
		 Ts.Decorate(jun);	    //穿上Ts	
		 Kz.Decorate(Ts);	    //穿上Kz
		 Oc.Decorate(Kz);      //穿上Oc
		 Oc.show();
		
}
}

// 人
class Person{
	
	private String name;
	double total;
	public Person() {
		  }
	public Person(String name) {
		this.name=name; 
	}
	 public void show() {
		 System.out.print(this.name+"  ");
	 }
	
}
//服饰类
class Finery extends Person{
	  protected Person component;
	  
	  //打扮
	  public void Decorate(Person component) {
		
		  this.component=component;
		  
	  }
	  
	  public void show() {
		  if(null!=component) {
			  
			 component.show();
			 
		  }
		  
	  }

		
	  
	  
}

//具体服饰类
class TShirts extends Finery{

	TShirts(){
		this.total=30;
	}
	
	@Override
	public void show() {
		// TODO Auto-generated method stub
		 super.show(); 
		 this.total+=component.total;
		System.out.println("大体恤30元  一共  "+this.total);
	}
}

//裤子
class Kuzi extends Finery{
	

	Kuzi(){
		this.total=80;
	}
	
	@Override
	public void show() {
		// TODO Auto-generated method stub
		super.show();	
		 this.total+=component.total;	
		System.out.println("裤子80元   一共" +this.total );
	}
	
}

class Overcoat extends Finery{
	

	Overcoat(){
		this.total=100;
	}
	
	@Override
	public void show() {
		// TODO Auto-generated method stub
		 super.show();	
		 this.total+=component.total;	
		 System.out.println("Overcoat100元   一共" +this.total );
	}
	
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值