简体   繁体   English

对象设计模式的已定义组合

[英]Defined combinations of objects design pattern

My head is hurting trying to figure out which would be the best design pattern after researching some on the internet. 在研究了一些互联网设计之后,我的头很想找出哪种设计是最好的。 The problem I am trying to solve, is the creation of combination of objects. 我要解决的问题是对象组合的创建。

For example, I have object combinations where an Event object will need to be created with a defined number of Task objects: 例如,我有一些对象组合,其中需要使用定义数量的Task对象创建一个Event对象:

Event 1 - Task 1, Task 2, Task 3 事件1-任务1,任务2,任务3

Event 2 - Task 2, Task 3 事件2-任务2,任务3

Ideally, I want a simple way of creating Event objects, without something like: 理想情况下,我想要一种简单的方法来创建事件对象,而无需类似以下内容:

Event.Add(Task1)
Event.Add(Task2)

etc etc Ideally I want to see something like Event1.Add(Task1).Add(Task2).Add(Task3). 等等等理想情况下,我想看到类似Event1.Add(Task1).Add(Task2).Add(Task3)的内容。

I also need to be able to retrieve the Tasks from Events as separate objects on their own. 我还需要能够将事件作为单独的对象从事件中检索出来。

And the Tasks need to be re-usable. 并且这些任务需要可重用。

How about a Builder Pattern 建造者模式怎么样

public class Event {
    public Event(IEnumerable<Task> tasks) {...}
}

with a builder api like so 用这样的构建器api

new EventBuilder().AddTask(....).AddTask(....).AddTask(....).Build();

You can do a little fluent foo like so... 您可以像这样做一点流利的foo ...

var e = new EventFoo().Add(new Task()).Add(new Task()) ; var e = new EventFoo().Add(new Task()).Add(new Task()) ;

public class EventFoo
{
    public EventFoo()
    {
        Tasks = new List<Task>();
    }
    public List<Task> Tasks { get; private set; }

    public EventFoo Add(Task task)
    {
        Tasks.Add(task);
        return this;
    }
}

If you have a regular set of events to create, you can also move their creation to a factory. 如果您要创建一组常规事件,则还可以将其创建移至工厂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM