代理模式--Java实现

相关类图

具体代码

//IntroductionAbstract.java
package org.example.test013;

public interface IntroductionAbstract {
    public void setAge(int age);
    public void findAnother();//找另一半
}

//IntroductionProxy.java
package org.example.test013;

public class IntroductionProxy implements IntroductionAbstract {
    private RealIntroduction realIntroduction = new RealIntroduction();

    public void setRealIntroduction(RealIntroduction a) {
        realIntroduction = a;
    }
    @Override
        public void setAge(int age) {

    }

    @Override
        public void findAnother() {
        if (realIntroduction.getAge() < 18) {
            System.out.println("未满18岁,对不起,不能早恋~");
        }
        else {
            realIntroduction.findAnother();
        }
    }
}

//RealIntroduction.java
package org.example.test013;

public class RealIntroduction implements IntroductionAbstract {

    private int AGE = 0;

    public int getAge() {
        return AGE;
    }
    @Override
        public void setAge(int age) {
        AGE = age;
    }

    @Override
        public void findAnother() {
        System.out.println("已经为您找到最佳伴侣~");
    }
}

//Client.java
package org.example.test013;

public class Client {
    public static void main(String[] args) {
        IntroductionProxy introductionProxy = new IntroductionProxy();
        RealIntroduction realIntroduction = new RealIntroduction();

        System.out.println("第一位客户15岁");
        realIntroduction.setAge(15);
        introductionProxy.setRealIntroduction(realIntroduction);
        introductionProxy.findAnother();

        System.out.println("-----------------------");
        System.out.println("第二位客户20岁");
        realIntroduction.setAge(20);
        introductionProxy.setRealIntroduction(realIntroduction);
        introductionProxy.findAnother();
    }
}

运行结果

posted @ 2023-11-16 08:51  yesyes1  阅读(2)  评论(0编辑  收藏  举报