开发者

Factory Pattern Question

I am a N00b to OO. and people throw flames at me for not answering or not having any points. what can I say except,I am not qualified!!!

Anyways here is my question I have seen more than enough examples of inheritance in your classic "Book" samples Animal, where Bear growls, Cat meows etc...

Let's say I am creating Windows 开发者_运维知识库Controls dynamically based on some data coming form(database, XML)

Let's say I create some static factory called CreateControl and I pass in the control type c for combobox, t for textbox etc so I have the following syntax Control c = CreateControl('c'); this returns to me a ComboBox

so far the factory pattern is working. anytime I want to introduce another control, I go to the factory pattern switch statement and add another control type.

In my winforms, for each control I create using this robust factory pattern I want to create eventhandlers based on what control I get back for example if I am creating ComboBox I create eventhandlers for 5 different events If the control is Textbox there are 2 events. so depending on what control is created there are different event handlers with different signatures.

some events require values coming from the form where the controls are sitting, some don't

I have this switch statement for declaring events based on controls I create! how do I take that part of the code in the code behind and do the right thing which is separation of concerns and little or zero code in the code behind!!

Thank you for your help


  1. Pass the type and not a char or string or whatever to the factory. Use the Activator to instantiate. This way the factory gains flexibility

  2. Pass the factory a Hashtable<Type, List> that tells for each control type which events to listen to.

  3. Start accepting answers. This can be done prior to 1 as well.


Your talk of switch statements sounds like you're missunderstanding what you are doing.

There are two types of Factory, a static helper which it sounds like what you're wanting / using and a dependency injection.

First what you're doing one or more static methods on a class that do common construction code for objects - so creating one and setting up it's event handlers. I'm not sure why you're passing in a letter rather than having one method per type created.

The second is a form of dependency injection where a factory interface is declared that has a method to create an object and then callers pass various implementations of the interface In to get different objects created, so one that creates Combos one that creates text controls.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜