关于java上下文的委托示例

什么是Java授权? 谁能给我一个恰当的例子?

这是代表团 – 与现实世界完全一样:

public interface Worker() { public Result work(); } public class Secretary() implements Worker { public Result work() { Result myResult = new Result(); return myResult; } } public class Boss() implements Worker { private Secretary secretary; public Result work() { return secretary.work(); } } 

(添加了Worker接口以更接近Delegator模式)

如果您指的是委托模式, 维基百科有一个很好的例子,用java编写 。

我相信上面这个页面的较长的例子是最好的:

 interface I { void f(); void g(); } class A implements I { public void f() { System.out.println("A: doing f()"); } public void g() { System.out.println("A: doing g()"); } } class B implements I { public void f() { System.out.println("B: doing f()"); } public void g() { System.out.println("B: doing g()"); } } class C implements I { // delegation I i = new A(); public void f() { if(); } public void g() { ig(); } // normal attributes void toA() { i = new A(); } void toB() { i = new B(); } } public class Main { public static void main(String[] args) { C c = new C(); cf(); // output: A: doing f() cg(); // output: A: doing g() c.toB(); cf(); // output: B: doing f() cg(); // output: B: doing g() } } 

与aioobe相同,但将类名更改为更直观的名称。 与现实世界的例子类比。

 public static void main(String[] args) { Boss boss = new Boss(); boss.toDeveloper(); boss.f(); boss.g(); boss.toSrDeveloper(); boss.f(); boss.g(); } interface I { void f(); void g(); } class Developer implements I { public void f() { System.out.println("Developer: f() is too hard for me."); } public void g() { System.out.println("Developer: g() is not in my domain."); } } class SrDeveloper implements I { public void f() { System.out.println("Sr. Developer: Okay, I'll see f()"); } public void g() { System.out.println("Sr. Developer: I'll do g() too."); } } class Boss implements I { // delegation I i; public void f() { if(); } public void g() { ig(); } void toDeveloper() { i = new Developer(); } void toSrDeveloper() { i = new SrDeveloper(); } } 

以下是如何使用委托的简单示例:

 interface IDogBehaviour { public void doThis(); } class BarkSound implements IDogBehaviour { public void doThis() { System.out.println("Bark!"); } } class WagTail implements IDogBehaviour { public void doThis() { System.out.println("Wag your Tail!"); } } class Dog { private IDogBehaviour sound = new BarkSound(); public void doThis() { this.sound.doThis(); } public void setNewBehaviour( IDogBehaviour newDo ){ this.sound = newDo; } } class DelegationDemo { public static void main( String args[] ){ Dog d = new Dog(); //delegation d.doThis(); //change to a new behaviour type - wag tail IDogBehaviour wag = new WagTail(); d.setNewBehaviour( wag ); //Delegation d.doThis(); } }