设计模式——代理模式

Posted on 2018-08-16 16:01  lhj1006400320  阅读(80)  评论(0编辑  收藏  举报

 

阿里云大学的课程挺不错,以下为代理模式这一节课的测试代码

https://edu.aliyun.com/lesson_35_327?spm=5176.8764728.0.0.EqRT7B#_327

package com.lhj.designPattern;

/**
 * 代理模式
 *      小明去餐馆吃饭,此时餐馆就是代理类,替小明洗菜,做菜,做饭,洗碗,扔垃圾
 * Pay Attention:
 *      1、餐馆和小明都需要继承同一个 吃饭的父类
 *      2、代理类需添加抽象父类属性
 *      3、代理类需添加有参构造,参数为真实代理的类
 *      4、真实操作前后,代理类可进行相应操作
 */
abstract class ToEat{
    public abstract void eat();
}

class XiaoMing extends ToEat{
    @Override
    public void eat() {
        System.out.println("进餐馆吃饭,付钱,然后就溜");
    }
}

class ProxyPerson extends ToEat{
    private ToEat person;
    public ProxyPerson(XiaoMing xiaoMing){
        this.person = xiaoMing;
    }

    @Override
    public void eat() {
        System.out.println("1、洗菜");
        System.out.println("2、做菜");
        System.out.println("3、做饭");
        person.eat();
        System.out.println("4、洗碗");
        System.out.println("5、扔垃圾");
    }
}

public class ProxyPatternTest {
    public static void main(String[] args) {
        ToEat xiaoming = new ProxyPerson(new XiaoMing());
        xiaoming.eat();
    }
}

 

Copyright © 2024 lhj1006400320
Powered by .NET 8.0 on Kubernetes