使用代理模式和无代理模式

时间:2015-07-31 14:22:32

标签: design-patterns proxy-pattern

我已经通过几个示例,但我没有发现任何示例与代理模式和没有代理模式显示相同的示例,

任何人都有一个通用的例子吗?通过看到这样的例子肯定会理解我们真的需要代理模式使用或不使用

1 个答案:

答案 0 :(得分:1)

只要需要比简单指针更通用或更复杂的对象引用,代理模式就适用。以下是代理模式适用的几种常见情况:

  • 控制对其他对象的访问
  • 延迟初始化
  • 实施日志记录
  • 促进网络连接
  • 计算对象的引用

举一个简单的例子,让我们考虑一组巫师想要进入塔楼的场景,但是有一个守护资源的代理,只允许三个第一个巫师通过。

public class Wizard {

    private String name;

    public Wizard(String name) {
        this.name = name;
    }

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

}

public class WizardTower {

    public void enter(Wizard wizard) {
        System.out.println(wizard + " enters the tower.");
    }

}

public class WizardTowerProxy extends WizardTower {

    private static final int NUM_WIZARDS_ALLOWED = 3;

    private int numWizards;

    @Override
    public void enter(Wizard wizard) {
        if (numWizards < NUM_WIZARDS_ALLOWED) {
            super.enter(wizard);
            numWizards++;
        } else {
            System.out.println(wizard + " is not allowed to enter!");
        }
    }
}

public class App {

    public static void main(String[] args) {

        WizardTowerProxy tower = new WizardTowerProxy();
        tower.enter(new Wizard("Red wizard"));
        tower.enter(new Wizard("White wizard"));
        tower.enter(new Wizard("Black wizard"));
        tower.enter(new Wizard("Green wizard"));
        tower.enter(new Wizard("Brown wizard"));

    }
}

控制台输出:

Red wizard enters the tower.
White wizard enters the tower.
Black wizard enters the tower.
Green wizard is not allowed to enter!
Brown wizard is not allowed to enter!

根据要求,以下是WizardTowerProxy代码合并到WizardTower的相同示例代码。

public class Wizard {

    private String name;

    public Wizard(String name) {
        this.name = name;
    }

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

public class WizardTower {

    private static final int NUM_WIZARDS_ALLOWED = 3;

    private int numWizards;

    public void enter(Wizard wizard) {
        if (numWizards < NUM_WIZARDS_ALLOWED) {
            System.out.println(wizard + " enters the tower.");
            numWizards++;
        } else {
            System.out.println(wizard + " is not allowed to enter!");
        }
    }
}

public class App {

    public static void main(String[] args) {

        WizardTower tower = new WizardTower();
        tower.enter(new Wizard("Red wizard"));
        tower.enter(new Wizard("White wizard"));
        tower.enter(new Wizard("Black wizard"));
        tower.enter(new Wizard("Green wizard"));
        tower.enter(new Wizard("Brown wizard"));
    }
}

控制台输出:

Red wizard enters the tower.
White wizard enters the tower.
Black wizard enters the tower.
Green wizard is not allowed to enter!
Brown wizard is not allowed to enter!