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

                                 设计模式——装饰模式

      最近在折腾java里的设计模式,在此把学习到的一些收获和一些源码都分享给大家。

      装饰模式 :

           interface (接口):  Person
           实现接口类: Man,Decorator .
           抽象类: Decorator
           子类: ManDecoratorA ,ManDecoratorB .
           测试类:   Test

    这是将要实现的装饰模式里的一些类。同时也把整个代码的思维导图画出来了,画思维导图是为了方便地写代码。

     根据这个图我们来构写代码:

    首先是接口部分
    
    public interface Person {
      
    	 void eat();
    }
    
     // Man类
    public class Man implements Person{
    
    	@Override
    	public void eat() {
    		// TODO 自动生成的方法存根
    		
    		System.out.println("男人在吃东西!");
    	}
    
    }

    public abstract class Decorator implements Person{
     
         protected Person person;   
        
          public void setPerson(Person person){
              this.person = person;
          }
           
           public void eat(){
              person.eat();
              
          }
          
          
        
        
    }

     上面的两个类实现了Person 这个接口。

    public class ManDecoratorA extends Decorator{
     
    	  public void eat(){
    		  
    		  super.eat();   // 继承父类的eat方法 
    		  reEat();
    		  System.out.println("This is " +" ManDecoratorA "+" Class");
    	  }  
    	  
    	  
    	  public void  reEat(){
    		  
    		  System.out.println("又吃了一顿!");
    	  }
    	
    	
    }
    
    public class ManDecoratorB extends Decorator{
       
    	public void eat()
       {
    	  super.eat(); 
    	  System.out.print("------------------------------------");
    	  System.out.print("
    ");
    	  System.out.print("------------------------------------");
    	  System.out.printf("
    ");
    	  System.out.println(" This is "+" ManDecoratorB "+" Class ");
    	  
       }
    	
    	
    }
    

     ManDecoratorA 和 ManDecoratorB 这两个子类继承了父类Decorator eat()方法,setPerson()方法

      测试类:

     

    public class Test {
    	public static void main(String[] args){
    		Man man = new Man();
    		ManDecoratorA md1 = new ManDecoratorA();
    		ManDecoratorB md2 = new ManDecoratorB();
    		 
    	   md1.setPerson(man);
    	   md2.setPerson(md1);
             md2.eat();		
    		
    		
    	}
    
    }
    

     运行结果:

     

  • 相关阅读:
    wireshark无法捕获无线网卡数据解决办法(failed to set hardware filter to promiscuous mode)
    用PHP检测用户是用手机(Mobile)还是电脑(PC)访问网站
    一次.net Socket UDP编程的10万客户端测试记录
    对象复制
    c#中volatile关键字的作用
    C#操作XML
    ASP.NET AJAX
    C#操作XMl2
    SQLServer 存储过程中不拼接SQL字符串实现多条件查询
    ASP.NET刷新页面的六种方法20081111 22:04asp.net页面刷新重是有问题,收藏几种方法挺有用的.
  • 原文地址:https://www.cnblogs.com/pwhit/p/5467046.html
Copyright © 2011-2022 走看看