代理模式

代理模式為另一個(gè)對(duì)象提供一個(gè)替身或占位符以控制對(duì)這個(gè)對(duì)象的訪問(wèn)。

示例—建立評(píng)價(jià)系統(tǒng)

每個(gè)人都有基本屬性,包括:名字、性別、興趣、評(píng)價(jià)率。需要對(duì)每個(gè)人的訪問(wèn)進(jìn)行控制,對(duì)名字、性別、興趣只能自己修改,別人不能修改。評(píng)價(jià)必須由其他人訪問(wèn),自己不能評(píng)價(jià)。

UML圖表示

代理模式

代碼演示

人的接口

package Proxy;

public interface PersonBean {

    String getName();
    String getGender();
    String getInterests();
    int getHotOrNotRating();

    void setName(String name);
    void setGender(String gender);
    void setInterests(String interests);
    void setHotOrNotRating(int rating);
}

人的實(shí)現(xiàn)類(lèi)

package Proxy;

public class PersonBeanImpl implements PersonBean {

    String name;
    String gender;
    String interests;
    int rating;
    int ratingCount = 0;

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getGender() {
        return gender;
    }

    @Override
    public String getInterests() {
        return interests;
    }

    @Override
    public int getHotOrNotRating() {
        if (ratingCount == 0) return 0;
        return (rating / ratingCount);
    }

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

    @Override
    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public void setInterests(String interests) {
        this.interests = interests;
    }

    @Override
    public void setHotOrNotRating(int rating) {
        this.rating += rating;
        ratingCount++;
    }
}

擁有者的動(dòng)態(tài)調(diào)用類(lèi)

package Proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class OwnerInvocationHandler implements InvocationHandler {

    PersonBean person;

    public OwnerInvocationHandler(PersonBean person){
        this.person = person;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException {
        try {
            if (method.getName().startsWith("get")){
                return method.invoke(person,args);
            }
            else if (method.getName().equals("setHotOrNotRating")){
                throw new IllegalAccessException();
            }
            else if (method.getName().startsWith("set")){
                return method.invoke(person,args);
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}

非擁有者的動(dòng)態(tài)調(diào)用類(lèi)

package Proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class NonOwnerInvocationHandler implements InvocationHandler {

    PersonBean person;

    public NonOwnerInvocationHandler(PersonBean person){
        this.person = person;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException {

        try {
            if (method.getName().startsWith("get")){
                return method.invoke(person,args);
            }
            else if (method.getName().equals("setHotOrNotRating")){
                return method.invoke(person,args);
            }
            else if (method.getName().startsWith("set")){
                throw  new IllegalAccessException();
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }
}

測(cè)試代碼

package Proxy;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class CommentTestDrive {

    Map<String,PersonBean> data;

    /**
     * 動(dòng)態(tài)生成擁有者代理類(lèi)
     * @param person
     * @return
     */
    PersonBean getOwnerProxy(PersonBean person){
        return (PersonBean) Proxy.newProxyInstance(person.getClass().getClassLoader(),
                person.getClass().getInterfaces(),new OwnerInvocationHandler(person));
    }

    /**
     * 動(dòng)態(tài)生成非擁有者代理類(lèi)
     * @param person
     * @return
     */
    PersonBean getNonOwnerProxy(PersonBean person){
        return (PersonBean) Proxy.newProxyInstance(person.getClass().getClassLoader(),
                person.getClass().getInterfaces(),new NonOwnerInvocationHandler(person));
    }

    /**
     * 初始化數(shù)據(jù)
     */
    void initializeDatabase(){
        data = new HashMap<String, PersonBean>();

        PersonBean person = new PersonBeanImpl();
        person.setName("Joe Javabean");
        person.setGender("male");
        person.setInterests("swimming");
        person.setHotOrNotRating(7);

        data.put("Joe", person);
    }

    public CommentTestDrive(){
        initializeDatabase();
    }

    public void drive(){
        PersonBean joe = data.get("Joe");

        System.out.println("His info is :");
        System.out.println("name is " + joe.getName());
        System.out.println("gender is " + joe.getGender());
        System.out.println("interests is " + joe.getInterests());
        System.out.println("rating is " + joe.getHotOrNotRating());
        System.out.println("~~~~~~~~~~~~~~~");

        PersonBean ownerProxy = getOwnerProxy(joe);
        System.out.println("Name is " + ownerProxy.getName());
        ownerProxy.setInterests("bowling, Go");
        System.out.println("Interests set from owner proxy");
        try {
            ownerProxy.setHotOrNotRating(10);
        }
        catch (Exception e){
            System.out.println("Can't set rating from owner proxy");
        }
        System.out.println("Rating is " + ownerProxy.getHotOrNotRating());

        PersonBean nonOwnerProxy = getNonOwnerProxy(joe);
        System.out.println("Name is " + nonOwnerProxy.getName());
        try {
            nonOwnerProxy.setInterests("bowling, Go");
        }
        catch (Exception e){
            System.out.println("Can't set interests from non owner proxy");
        }

        nonOwnerProxy.setHotOrNotRating(3);
        System.out.println("Rating set from non owner proxy");
        System.out.println("Rating is " + nonOwnerProxy.getHotOrNotRating());


        System.out.println("~~~~~~~~~~~~~~~");
        System.out.println("Now his info is :");
        System.out.println("name is " + joe.getName());
        System.out.println("gender is " + joe.getGender());
        System.out.println("interests is " + joe.getInterests());
        System.out.println("rating is " + joe.getHotOrNotRating());

    }

    public static void main(String[] args) {
        CommentTestDrive drive = new CommentTestDrive();
        drive.drive();
    }

}

測(cè)試結(jié)果

His info is :
name is Joe Javabean
gender is male
interests is swimming
rating is 7
~~~~~~~~~~~~~~~
Name is Joe Javabean
Interests set from owner proxy
Can't set rating from owner proxy
Rating is 7
Name is Joe Javabean
Can't set interests from non owner proxy
Rating set from non owner proxy
Rating is 5
~~~~~~~~~~~~~~~
Now his info is :
name is Joe Javabean
gender is male
interests is bowling, Go
rating is 5
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容