/** * Decoration test */publicclassDecoration{publicstaticvoidmain(Stringargs[]){Plumberplumber=newPlumber();AWorkeraWorker=newAWorker(plumber);aWorker.doSomeWork();Carpentercarpenter=newCarpenter();BWorkerbCarpenter=newBWorker(carpenter);bCarpenter.doSomeWork();}}interfaceWorker{voiddoSomeWork();}classPlumberimplementsWorker{publicvoiddoSomeWork(){System.out.println("Plumber do some work!");}}classCarpenterimplementsWorker{publicvoiddoSomeWork(){System.out.println("Carpenter do some work!");}}classAWorkerimplementsWorker{privateWorkertempWorker;publicAWorker(Workerworker){tempWorker=worker;}publicvoiddoSomeWork(){System.out.println("Hello,I am a A worker");tempWorker.doSomeWork();// use the Worker class method}}// use temp Worker, avoid "this"classBWorkerimplementsWorker{privateWorkerworker;publicBWorker(Workerworker){this.worker=worker;}publicvoiddoSomeWork(){System.out.println("Hello,I am a B worker");worker.doSomeWork();}}
输出:
Hello,I am a A worker
Plumber do some work!
Hello,I am a B worker
Carpenter do some work!