我有单身课程World。(它不需要是单例的,但它在我的项目中是这样定义的。)
然后我有Component接口,然后由ConcreteComponent1等ConcreteComponent2实现。这些都实现了一些不错的方法,例如decorateTheWorld.
在某个时候,World实例会遍历它Compontent的所有孩子,并要求他们通过调用它们来装饰自己decorateTheWorld。
这种方法的问题是World, 或之外的东西World需要知道任何类型Component的Worldcan ,因为Component需要在某个时候以某种方式创建实例。
关键是我不想做一些愚蠢的事情,比如 100 行重复的代码,比如
(new ConcreteComponent1())->registerInTheWorld()
(new ConcreteComponent2())->registerInTheWorld()
(new ConcreteComponent3())->registerInTheWorld()
...我不想诉诸反思。
那么,是否有任何设计模式可以自动使注册部分开箱即用?还是我要求不可能?