• java 装饰者模式


    IPerson:

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-20 下午3:43:04
     */
    public interface IPerson {
        public void canDo();
    }

    Person:

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-20 下午3:44:04
     */
    public class Person implements IPerson{
    
        @Override
        public void canDo() {
            System.out.println("I can code");
        }
    }

    Decorator(所有Person装饰者的父类):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-20 下午3:44:55
     */
    public class Decorator implements IPerson{
        private IPerson person;
        public Decorator(IPerson person) {
            this.person = person;
        }
    
        @Override
        public void canDo() {
            person.canDo();
        }
    }

    DecoratorSwim(Swim装饰--为Peron添加“Swim”功能):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-20 下午3:48:54
     */
    public class DecoratorSwim extends Decorator{
    
        public DecoratorSwim(IPerson person) {
            super(person);
        }
        
        @Override
        public void canDo() {
            super.canDo();
            System.out.println("I also can swim");
        }
    }

    DecoratorDraw(Draw装饰--为Peron添加“Draw”功能):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-20 下午3:47:29
     */
    public class DecoratorDraw extends Decorator{
    
        public DecoratorDraw(IPerson person) {
            super(person);
        }
        @Override
        public void canDo() {
            super.canDo();
            System.out.println("I also can draw");
        }
    }

    Test:

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-20 下午3:49:35
     */
    public class Test {
        public static void main(String[] args) {
            Decorator decorator = new DecoratorDraw(new DecoratorSwim(new Person()));
            decorator.canDo();
        }
    }
  • 相关阅读:
    进程和线程的一个简单形象的解释
    java流的性能优化1-文件复制
    JAVA修饰符类型(public,protected,private,friendly)
    Codeforces Round #252 (Div. 2) 441B. Valera and Fruits
    游戏开场镜头拉近(Unity3D开发之四)
    P1282 多米诺骨牌
    P1280 尼克的任务
    求最小生成树(暴力法,prim,prim的堆优化,kruskal)
    暴力求最短路
    用MyEclipse将java文件转换成UML类图
  • 原文地址:https://www.cnblogs.com/tiantianbyconan/p/2779194.html
Copyright © 2020-2023  润新知