Composite

  • 用树形结构分层
  • 通过统一对待来简化操作

企业微信20210616-161732@2x.png

  1. interface Component {
  2. operation: Function;
  3. }
  4. abstract class Leaf implements Component {
  5. operation() {}
  6. }
  7. abstract class Composite implements Component {
  8. protected childs: Component[] = [];
  9. operation() {
  10. this.childs.forEach(child => {
  11. child.operation();
  12. });
  13. }
  14. add(component: Component) {
  15. this.childs.push(component);
  16. }
  17. remove(component: Component) {
  18. this.childs.splice(this.childs.indexOf(component), 1);
  19. }
  20. getChild() {
  21. return this.childs;
  22. }
  23. }
  24. class Duck extends Composite {
  25. constructor(childs: Component[]) {
  26. super();
  27. this.childs = childs;
  28. }
  29. }
  30. class DuckVoice extends Leaf {
  31. operation() {
  32. console.log('Quack.');
  33. }
  34. }
  35. class DuckFly extends Composite {
  36. operation() {
  37. console.log('It flies.');
  38. super.operation();
  39. }
  40. add(component: Component) {
  41. super.add(component);
  42. return this;
  43. }
  44. }
  45. class Wing extends Leaf {
  46. operation() {
  47. console.log('Flap-flap-flap');
  48. }
  49. }
  50. const wings = [new Wing(), new Wing()];
  51. const flyAbility = new DuckFly().add(wings[0]).add(wings[1]);
  52. const voiceAbility = new DuckVoice();
  53. const duck = new Duck([flyAbility, voiceAbility]);
  54. duck.operation();

参考资料

  1. 24 | 组合模式:如何用树形结构处理对象之间的复杂关系?
  2. 组合模式
  3. The Composite Pattern for TypeScript Developers