gpt4 book ai didi

php - 自注册组件/插件的设计模式

转载 作者:行者123 更新时间:2023-12-04 04:59:30 26 4
gpt4 key购买 nike

我有单例类(class)World . (它不需要是单例的,但它在我的项目中是这样定义的。)

然后我有 Component接口(interface),然后由ConcreteComponent1实现, ConcreteComponent2等等。这些都实现了一些不错的方法,如 decorateTheWorld .

在某些时候,World然后实例将遍历其所有子 Compontent s 并要求他们通过调用 decorateTheWorld 来装饰自己在他们。

这种方法的问题是 World , 或 World 之外的内容然后需要知道任何类型的Component World可以有,因为 Component需要在某个时候以某种方式创建实例。

关键是我不想做一些愚蠢的事情,比如 100 行重复的代码,比如

(new ConcreteComponent1())->registerInTheWorld()
(new ConcreteComponent2())->registerInTheWorld()
(new ConcreteComponent3())->registerInTheWorld()

...和我 不要想诉诸反射(reflection)。

那么,是否有任何设计模式可以自动使注册部分开箱即用?还是我要求不可能?

最佳答案

只要组件实现了一个通用接口(interface),你的世界就不必知 Prop 体的组件,只需要知道接口(interface)。

请参阅此示例(C#):

public interface IComponent
{
void decorateTheWorld();
}

public class ComponentA : IComponent
{
public void decorateTheWorld() { /* ... */ }
}

public class ComponentB : IComponent { /* ... */ }

在您的世界级中,假设 _componentsIComponent 的集合年代:
foreach(IComponent comp in _components)
comp.decorateTheWorld();

现在,如果您不想手动“查找”组件,您可以从已加载的程序集中获取所有类型并找到实现 IComponent 的组件。然后使用 Activator.CreateInstance 实例化它们.

关于php - 自注册组件/插件的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16315127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com