0

我已经浏览了几个示例,但我没有找到任何显示相同示例的示例使用代理模式和不使用代理模式,

有人有一个通用的例子吗?通过看到这样的例子肯定会明白我们是否真的需要使用代理模式

4

1 回答 1

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!
于 2015-08-02T06:56:26.713 回答