Java/C++实现代理模式---婚介所

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

类图:

Java/C++实现代理模式---婚介所

 

Java代码:

public abstract class Center
{
    protected String name;
    public Center(String name){this.name=name;}
    public abstract void findlove(Person person);
}


public class Marry extends Center
{
     public Marry(String name){super(name);}
        public void findlove(Person person)
        {
            if(person.getAge()<18)
            {
                System.out.println(name+":"+person.getName()+",对不起!不能早恋!");
            }
            else if(person.getAge()<100)
            {
                System.out.println(name+":"+person.getName()+",我们会为您找到合适的伴侣!");
            }
            else
            {
                System.out.println(name+":"+person.getName()+",对不起!您年龄太大了!");
            }
        }
}

public class Person {
    protected String name;
    protected int age;

    public Person(String name,int age)
    {
        this.name=name;
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class Client
{
    public static void main(String args[])
    {
        Center center1,center2;
        center1=new Marry("婚介");
        center2=new Marry("婚介");
        Person b1=new Person("喜羊羊",29);
        Person b2=new Person("美羊羊",16);
        center1.findlove(b1);
        center2.findlove(b2);
    }

}

C++代码:

#include <iostream>
#include <string>
using namespace std;


class Person
{
public:
    string name;
    int age;
    Person(string n,int a)
    {
        name=n;
        age=a;
    }
};

class Center
{
protected:
    string name;
public:
    Center(string n){name=n;}
    virtual void findlove(Person* person)=0;
};


class Marry:public Center
{
public:
    Marry(string name):Center(name){}
    void findlove(Person* person)
    {
        if(person->age<18)
        {
            cout <<name<<":"<<person->name<<",对不起!不能早恋!" << endl;
        }
        else if(person->age<100)
        {
            cout <<name<<":"<<person->name<<",我们会为您找到合适的伴侣!" << endl;
        }
        else
        {
            cout <<name<<":"<<person->name<<",对不起!您年龄太大了!" << endl;
        }
    }
};



int main()
{
    Center* center1,* center2;
    center1=new Marry("婚介");
    center2=new Marry("婚介");
    Person* b1=new Person("喜羊羊",29);
    Person* b2=new Person("美羊羊",16);
    center1->findlove(b1);
    center2->findlove(b2);
    return 0;
}

运行结果:

Java/C++实现代理模式---婚介所

 

 Java/C++实现代理模式---婚介所

 

上一篇:基于poll的echo服务器(回显服务器)


下一篇:RUST 学习日记 第12课 ——切片