// 以动物园模拟为例,我们有几种不同种类的动物,它们能够发出不同的声音。classMonkey{shout(){ console.log("Ooh oo aa aa!");}accept(operation){ operation.visitMonkey(this);}}classLion{roar(){ console.log("Roaaar!");}accept(operation){ operation.visitLion(this);}}classDolphin{speak(){ console.log("Tuut tuttu tuutt!");}accept(operation){ operation.visitDolphin(this);}}const speak ={visitMonkey(monkey){ monkey.shout();},visitLion(lion){ lion.roar();},visitDolphin(dolphin){ dolphin.speak();}};(function(){const monkey =newMonkey();const lion =newLion();const dolphin =newDolphin(); monkey.accept(speak);// Ooh oo aa aa! lion.accept(speak);// Roaaar! dolphin.accept(speak);// Tuut tutt tuutt!})();// 我们可以通过对动物具有继承层次结构来简单地做到这一点// 但是每当必须向动物添加新动作时,我们就必须修改动物。// 而现在我们不必更改它们。// 例如,假设我们被要求将跳跃行为添加到动物中,我们可以简单地通过创建一个新的访客来添加它。const jump ={visitMonkey(monkey){ console.log("Jumped 20 feet high! on to the tree!");},visitLion(lion){ console.log("Jumped 7 feet! Back on the ground!");},visitDolphin(dolphin){ console.log("Walked on water a little and disappeared");}};(function(){const monkey =newMonkey();const lion =newLion();const dolphin =newDolphin(); monkey.accept(speak);// Ooh oo aa aa! monkey.accept(jump);// Jumped 20 feet high! on to the tree! lion.accept(speak);// Roaaar! lion.accept(jump);// Jumped 7 feet! Back on the ground! dolphin.accept(speak);// Tuut tutt tuutt! dolphin.accept(jump);// Walked on water a little and disappeared})();