14. 代理模式

[实验任务一]:婚介所

婚介所其实就是找对象的一个代理,请仿照我们的课堂例子“论坛权限控制代理”完成这个实际问题,其中如果年纪小于18周岁,婚介所会提示“对不起,不能早恋!”,并终止业务。

类图

image

代码

java版

package test14;

public interface AbstractPermission {

    public void findFriend();

}
package test14;

public class Client {

    public static void main(String[] args) {
        AbstractPermission permission = new PermissionProxy(16);
        permission.findFriend();
    }

}
package test14;

public class PermissionProxy implements AbstractPermission{

    private RealPermission permission = new RealPermission();
    private int age;

    public PermissionProxy(int age){
        this.age = age;
    }

    @Override
    public void findFriend() {
        if(age<18){
            System.out.println("对不起,不能早恋");
        }else {
            permission.findFriend();
        }
    }
}
package test14;

public class RealPermission implements AbstractPermission{
    @Override
    public void findFriend() {
        System.out.println("找npy");
    }
}

c++版

#include <iostream>
using namespace std;

class AbstractPermission{
public:
    AbstractPermission(){}
    virtual void findFriend(){};
};

class RealPermission: public AbstractPermission{
public:
    RealPermission():AbstractPermission(){

    }
    void findFriend(){
        cout<<"找npy";
    }
};

class PermissionProxy: public AbstractPermission{
private:
    RealPermission* permission = new RealPermission();
    int age;
public:
    PermissionProxy(int age):AbstractPermission(){
        this->age = age;
    }
    void findFriend(){
        if(age<18){
            cout<<"对不起,不能早恋";
        } else{
            permission->findFriend();
        }
    }
};

int main(){
//    AbstractPermission* permission = new AbstractPermission();
    PermissionProxy* permissionProxy = new PermissionProxy(16);

//    permission = permissionProxy;
    permissionProxy->findFriend();
}
posted @ 2022-10-13 16:41  又一岁荣枯  阅读(38)  评论(0编辑  收藏  举报