Why do we need the decorator in the decorator design pattern?

后端 未结 3 1914
渐次进展
渐次进展 2020-12-03 03:29

Presuming I have a class named A, and I want to use the decorator design pattern. Correct me if I\'m wrong, but for that to work , we\'ll need to create a decor

3条回答
  •  再見小時候
    2020-12-03 04:10

    In some languages (like Ruby or JavaScript) you could just add new functionality to an A instance. I notice that your question is tagged Java, so I assume that you are asking why you can't do this in Java. The reason is that Java is statically typed. An A instance can only ever have the methods that class A defines or inherits. Therefore, if you want at run time to give an A instance a method that A does not define, then this new method must be defined in a different class.

提交回复
热议问题