I'm having some problems trying to figure out how to solve a problem without being able to have static method in an abstract class or interface. Consider the following code. I have many Wizards that inherit from AbsWizard. Each wizard has a method GetMagic(string spell) that only returns magic for certain magic words, yet all instances of a specific type of wizard respond to the same set of magic words.
public abstract class AbsWizard
{
public abstract Magic GetMagic(String magicword);
public abstract string[] GetAvalibleSpells();
}
public class WhiteWizard : AbsWizard
{
public override Magic GetMagic(string magicword)
{
//returns some magic based on the magic word
}
public override string[] GetAvalibleSpells()
{
string[] spells = {"booblah","zoombar"};
return spells;
}
}
public class BlackWizard : AbsWizard
{
public override Magic GetMagic(string magicword)
{
//returns some magic based on the magic word
}
public override string[] GetAvalibleSpells()
{
string[] spells = { "zoogle", "xclondon" };
return spells;
}
}
I want the user to be able to first choose the type of wizard, and then be presented with a list of the spells that type of wizard can cast. Then when they choose a spell the program will find all, if any, existing wizards of the selected type and have them cast the selected spell. All wizards of a specific type will always have the same available spells, and I need a way to determine the spells a specific type of wizard can cast with out actually having access to an instance of the selected type of wizard.
In addition I don't want to have to depend on a separate list of possible wizard types or spells. Instead I would rather just infer everything through GetAvalibleSpells() and reflection. For example I plan to cast magic as follows:
public static void CastMagic()
{
Type[] types = System.Reflection.Assembly.GetExecutingAssembly().GetTypes();
List<Type> wizardTypes = new List<Type>();
List<string> avalibleSpells = new List<string>();
Type selectedWizardType;
string selectedSpell;
foreach (Type t in types)
{
if (typeof(AbsWizard).IsAssignableFrom(t))
{
wizardTypes.Add(t);
}
}
//Allow user to pick a wizard type (assign a value to selectedWizardType)
//find the spells the selected type of wizard can cast (populate availibleSpells)
//Alow user to pick the spell (assign a value to selectedSpell)
//Find all instances, if any exsist, of wizards of type selectedWizardType and call GetMagic(selectedSpell);
}
I think this is very bad style. You write the code, so you should know what wizard-classes you have in there. It's very bad style (and slow!) to run through all types via reflection and check if they derive from AbsWizard.
The Managed Extensibility Framework (available through codeplex for pre-.NET-4.0, or built-in .NET 4.0 in the System.ComponentModel.Composition namespace) was built for this. Say you have a service that can ask a user to select a wizard and then create it. It uses a wizard provider to create the wizards, and needs to know the name and available spells (metadata) for the wizards that a provider creates. You might use interfaces like these:
namespace Wizardry
{
using System.Collections.Generic;
public interface IWizardProvider
{
IWizard CreateWizard();
}
public interface IWizard
{
IMagic GetMagic(string magicWord);
}
public interface IWizardProviderMetadata
{
string Name { get; }
IEnumerable<string> Spells { get; }
}
}
The wizard creation service imports the available wizard providers, selects one through some mechanism (user feedback in your case), and uses the provider to create the wizard.
namespace Wizardry
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
public class UserWizardCreationService
{
[Import]
private IEnumerable<Lazy<IWizardProvider, IWizardProviderMetadata>> WizardProviders { get; set; }
public IWizard CreateWizard()
{
IWizard wizard = null;
Lazy<IWizardProvider, IWizardProviderMetadata> lazyWizardProvider = null;
IWizardProvider wizardProvider = null;
// example 1: get a provider that can create a "White Wizard"
lazyWizardProvider = WizardProviders.FirstOrDefault(provider => provider.Metadata.Name == "White Wizard");
if (lazyWizardProvider != null)
wizardProvider = lazyWizardProvider.Value;
// example 2: get a provider that can create a wizard that can cast the "booblah" spell
lazyWizardProvider = WizardProviders.FirstOrDefault(provider => provider.Metadata.Spells.Contains("booblah"));
if (lazyWizardProvider != null)
wizardProvider = lazyWizardProvider.Value;
// finally, for whatever wizard provider we have, use it to create a wizard
if (wizardProvider != null)
wizard = wizardProvider.CreateWizard();
return wizard;
}
}
}
You can then create and export an arbitrary number of wizard providers with spells, and the creation service will be able to find them:
namespace Wizardry
{
using System.ComponentModel.Composition;
[Export(typeof(IWizardProvider))]
[Name("White Wizard")]
[Spells("booblah", "zoombar")]
public class WhiteWizardProvider : IWizardProvider
{
public IWizard CreateWizard()
{
return new WhiteWizard();
}
}
[Export(typeof(IWizardProvider))]
[Name("White Wizard")]
[Spells("zoogle", "xclondon")]
public class BlackWizardProvider : IWizardProvider
{
public IWizard CreateWizard()
{
return new BlackWizard();
}
}
}
Of course you'll need to implement the wizards as well.
namespace Wizardry
{
using System;
public class WhiteWizard : IWizard
{
public IMagic GetMagic(string magicWord)
{
throw new NotImplementedException();
}
}
public class BlackWizard : IWizard
{
public IMagic GetMagic(string magicWord)
{
throw new NotImplementedException();
}
}
}
To keep things clean, this code uses a custom NameAttribute and SpellsAttribute as a much cleaner form of exporting metadata than ExportMetadataAttribute:
namespace Wizardry
{
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public abstract class MultipleBaseMetadataAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public abstract class SingletonBaseMetadataAttribute : Attribute
{
}
public sealed class NameAttribute : SingletonBaseMetadataAttribute
{
public NameAttribute(string value) { this.Name = value; }
public string Name { get; private set; }
}
public sealed class SpellsAttribute : MultipleBaseMetadataAttribute
{
public SpellsAttribute(params string[] value) { this.Spells = value; }
public string[] Spells { get; private set; }
}
}
Add another level of indirection. The GetAvailableSpells method isn't really an instance method, since it's the same for all instances. As you pointed you, you can't have an abstract static method, so instead move the type-specific stuff into an instance-based class factory. In the example below, AvailableSpells is a method of the MagicSchool abstract class, which has concrete subclasses BlackMagic, WhiteMagic, etc. The Wizard also has sub-types, but every Wizard can return the MagicSchool that it belongs to, giving you a type-safe, type-independent way to find out what the spells for any given Wizard object are without separate tables or code duplication.
public abstract class MagicSchool
{
public abstract string[] AvailableSpells { get; }
public abstract Wizard CreateWizard();
}
public abstract class Wizard
{
protected Wizard(MagicSchool school)
{
School = school;
}
public abstract Cast(string spell);
MagicSchool School
{
public get;
protected set;
}
}
public class BlackMagic : MagicSchool
{
public override AvailableSpells
{
get
{
return new string[] { "zoogle", "xclondon" };
}
}
public override Wizard CreateWizard()
{
return new BlackWizard(this);
}
}
public class BlackWizard : Wizard
{
public BlackWizard(BlackMagic school)
: base(school)
{
// etc
}
public override Cast(string spell)
{
// etc.
}
}
// continue for other wizard types
First, you should really consider whether you can't bend the rules of not using instances of Wizards to discover their available spells. I find that the prototype pattern can actually be quite useful for this sort of thing.
However, if you really can't do that, you can use nested classes and reflection to discover the available spells that a particular concrete AbsWizard-derivative can cast. Here's an example:
public abstract class AbsWizard
{
public abstract Magic GetMagic(String magicword);
public abstract string[] GetAvalibleSpells();
}
public class WhiteWizard : AbsWizard
{
// organizes all the spells available to the wizard...
public sealed class Spells
{
// NOTE: Spells may be better off as a specific class, rather than as strings.
// Then you could decorate them with a lot of other information (cost, category, etc).
public const string Abracadabra = "Abracadabra";
public const string AlaPeanutButterSandwiches = "APBS";
}
}
public static void CastMagic()
{
Type[] types = System.Reflection.Assembly.GetExecutingAssembly().GetTypes();
List<Type> wizardTypes = new List<string>();
List<string> avalibleSpells = new List<string>();
Type selectedWizardType;
string selectedSpell;
foreach (Type t in types)
{
if (typeof(AbsWizard).IsAssignableFrom(t))
{
// find a nested class named Spells and search it for public spell definitions
// better yet, use an attribute to decorate which class is the spell lexicon
var spellLexicon = Type.FromName( t.FullName + "+" + "Spells" );
foreach( var spellField in spellLexicon.GetFields() )
// whatever you do with the spells...
}
}
}
There are many ways to improve the above code.
First, you can define your own custom attribute that you can tag on the nested classes of each wizard to identify the spell lexicon.
Second, using strings to define the available spells may end up being a bit limiting. You may find it easier to define a global static list of all available spells (as some kind of class, let's call it Spell). You could then define the available spells of the wizard based off this list, rather than strings.
Third, consider creating an external configuration for this thing rather than embedded, nested classes. It's more flexible and possibly easier to maintain. However, it can be nice to write code like:
WhiteWizard.Spells.Abracadabra.Cast();
Finally, consider creating a static dictionary for each Wizard-derivative that manages the list of available spells so that you can avoid performing reflection (which is expensive) more than once.
Since spells are tied to the type of the wizard, I'd do this through attributes:
[AttributeUsage(AttributeTargets.Class)]
public class SpellsAttribute : Attribute
{
private string[] spells;
public WizardAttribute(params string[] spells)
{
this.spells = spells;
}
public IEnumerable<string> Spells
{
get { return this.spells ?? Enumerable.Empty<string>(); }
}
}
Then you declare a wizard type like this:
[Spells("booblah","zoombar")]
public class WhiteWizard : AbsWizard
{
public override Magic GetMagic(string magicWord) { ... }
}
Then the class that loads wizard types from the assembly can check each wizard class has this attribute and if so makes the type available (or throws an exception).
Does this do what you need? Add each type of wizard to the factory as needed. Wizards will never be instantiated outside of your library, only inside it. For someone outside your library to get a wizard, they make a call to the factory to get those wizards that support a given spell. The factory sets itself up. Just register each new wizard with the factory.
public class Magic
{
}
public abstract class AbsWizard
{
public abstract Magic GetMagic(String magicword);
public abstract string[] GetAvalibleSpells();
internal AbsWizard()
{
}
}
public class WhiteWizard : AbsWizard
{
public override Magic GetMagic(string magicword)
{
return new Magic();
}
public override string[] GetAvalibleSpells()
{
string[] spells = { "booblah", "zoombar" };
return spells;
}
}
public static class WizardFactory
{
private static Dictionary<string, List<AbsWizard>> _spellsList = new Dictionary<string, List<AbsWizard>>();
/// <summary>
/// Take the wizard and add his spells to the global spell pool. Then register him with that spell.
/// </summary>
/// <param name="wizard"></param>
private static void RegisterWizard(AbsWizard wizard)
{
foreach (string s in wizard.GetAvalibleSpells())
{
List<AbsWizard> lst = null;
if (!_spellsList.TryGetValue(s, out lst))
{
_spellsList.Add(s, lst = new List<AbsWizard>());
}
lst.Add(wizard);
}
}
public string[] GetGlobalSpellList()
{
List<string> retval = new List<string>();
foreach (string s in _spellsList.Keys)
{
retval.Add(s);
}
return retval.ToArray<string>();
}
public List<AbsWizard> GetWizardsWithSpell(string spell)
{
List<AbsWizard> retval = null;
_spellsList.TryGetValue(spell, out retval);
return retval;
}
static WizardFactory()
{
RegisterWizard(new WhiteWizard());
}
}
Use a factory class to instantiate your wizards. The factory has a
public static string[] GetSpellsForWizardType(Type wizardType)
method that allows you to determine which spells a wizard can cast. The factory also calls this same method to construct a new wizard instance and set its spell set.
Related
I am writing a tranformer that takes some input and gives an output.I need to call a specific tranformer based on my input type.
public static myentrypoint( template t);
{
//I could do something like this.
switch(t)
{
case t1:
transformt1(..);
case t2:
transformt1(..);
....
}
}
Trasform1 : Itransform
{
tranform1(...);
}
Trasform2 : Itransform
{
tranform2(...);
}
I need to map which function to call based on what my template is. I can do a switch but are there more cleaner ways to do this using some design patterns ? I was thinking a of writing a static dictionary. I am new to OOP so any suggestions would be great.
If template is a class, and each template potentially has a different transform, then why not just include the transform function inside of your template class?
public static myentrypoint( ITemplate t);
{
t.transform();
}
The way that I do these types of situations is through the use of Generics. (Shameless self-promotion of a blog post)
Basically, you'll have your base class set up like this:
public abstract class Transformer<T>
where T : Template
{
public abstract void Transform(T item);
}
Then you derive for each of your types like this:
public class Transformer1 : Tansformer<Template1>
{
public void Transform(Template1 item)
{
}
}
public class Transformer2 : Transformer<Template2>
{
public void Transform(Template2 item)
{
}
}
Then you'll just need a factory to give you the correct Transformer.
public class TransformFactory
{
public Transformer<T> GetTransformer<T>(T item)
{
if (item is Template1)
return new Transformer1();
else if (item is Template2)
return new Transformer2();
// ...
}
}
The benefit of this approach is that you'll be able to encapsulate all behavior on that specific type in the concrete implementations. If there is any common behavior on them all, you can do that in the abstract base.
Invoking methods based on a parameter without switch-case statements in C#
In OOP, based on the [open/close principle] which says that software entities such as classes and functions should be open for extension, but closed
for modification.
Methods which use switch-case statement would call this principle into question. In order to implement this principle inside the codes without
causing changes in their functionality.
We use a pattern named "Delegate Dictionary Pattern".
For example, we have an entity named Template that keep input values as well as some of Transform classes for processing this Template.
Template class for keeping input value
public class Template
{
public int TransformNo { get; set; }
public string Title { get; set; }
}
ITransform interface for transform abstract
public interface ITransform
{
void Do(Template template);
}
Transform1 as a concrete class of ITransform
public class Transform1 : ITransform
{
public void Do(Template template)
{
Console.WriteLine($"Transform : {template.TransformNo}, TemplateTitle : { template.Title}");
}
}
Transform2 as a concrete class of ITransform
public class Transform2 : ITransform
{
public void Do(Template template)
{
Console.WriteLine($"Transform : {template.TransformNo}, TemplateTitle : { template.Title}");
}
}
TransformCordinator class for coordinating template of *ITransformer**
public class TransformCordinator
{
Dictionary<int, Action<Template>> transformMap = new Dictionary<int, Action<Template>>();
public TransformCordinator()
{
transformMap.Add(1, x => new Transform1().Do(x));
transformMap.Add(2, x => new Transform2().Do(x));
}
public void Do(Template template)
{
transformMap[template.TransformNo](template);
}
}
// example
class Program
{
static void Main(string[] args)
{
var transformCordinator = new TransformCordinator();
transformCordinator.Do(new Template() { TransformNo = 1, Title = "Hi!" });
Console.ReadLine();
}
}
[MAJOR EDITS, my first post was somewhat misleading. My appologies]
Given a class such as:
public class DatabaseResult{
public bool Successful;
public string ErrorMessage;
//Database operation failed
public static DatabaseResult Failed(string message) {
return new DatabaseResult{
Successful = true,
ErrorMessage = message
};
}
}
How can I implement subclasses such that I can add additional properties to represent data relevant to the particular operation (such as MatchedResult in the case of a SELECT type query) without the need to implement that static failure function? If I try to use plain inheritance, the return type will be of the parent class. Eg:
DoThingDatabaseResult : DatabaseResult {
public IEnumerable<object> SomeResultSet;
public static Successful(IEnumerable<object> theResults){
return new DoThingDatabaseResult {
Successful = true,
ErrorMessage = "",
SomeResultSet = theResults
};
}
//public static DatabaseResult Failed exists, but it's the parent type!
}
The goal is to avoid needing to copy the Failed static function for every subclass implementation.
Make it recursively generic:
public class BankAccount<T> where T : BankAccount<T>, new()
{
public T SomeFactoryMethod() { return new T(); }
}
public class SavingsAccount: BankAccount<SavingsAccount>{}
You'll note that I made the factory method non-static, because static methods aren't inherited.
You can't do this exactly as you have defined the question. The best way to tackle this is really to pull your factory out of the class completely:
public class BankAccount
{
}
public class SavingsAccount : BankAccount
{
}
public static class BankAccountFactory
{
public static T Create<T>() where T : BankAccount, new()
{
return new T();
}
}
Now the Factory has no dependency on the actual type. You can pass any derived class of BankAccount and get it back without doing any extra work or worrying about inheriting your factory method.
If I may, I'd like to expand upon StriplingWarrior. In fact, you can use static for the factory. This following code shows that a and c are the expected object types. The limit is you cannot use the factory on the base class itself.
private void Testit()
{
var a = SavingsAccount.Factory();
var c = CheckingAccount.Factory();
//var b = BankAccount.Factory(); //can't do this
}
public class BankAccount<T> where T : BankAccount<T>, new()
{
public static T Factory()
{
return new T();
}
}
public class SavingsAccount : BankAccount<SavingsAccount>
{
}
public class CheckingAccount : BankAccount<CheckingAccount>
{
}
In order to use inheritance, you need an instance of an object and a member of that object. In this case, for the object we can't use BankAccount/SavingsAccount because then we would already have what we're trying to get. This means we need an actual factory object, which is what most people are talking about when they talk about a factory. So if we pull that out into a Factory and use inheritance...
public class BankAccountFactory { public virtual GetAccount() { return new BankAccount(); } }
public class SavingsAccountFactory : BankAccountFactory { public override GetAccount() { return new SavingsAccount(); } }
But now how do we get an instance of the proper type? We've just pushed our problem one layer deeper.
Instead, what you probably want to do, is use some sort of configuration to determine the type, or pass the type you want into a method.
public BankAccount GetAccount(AccountType type) { /* */ }
or
public BankAccount GetAccount() { /* Access config */ }
For a simple answer to your question: You don't need to use generics or anything like that, you just need your method to not be static...
I have a 3rd party badly designed library that I must use.
It has all sorts of types it works with, we'll call them SomeType1, SomeType2 etc.
None of those types share a common base class but all have a property named Value with a different return type.
All I want to do is to be able to Mixin this class so I'll be able to call someType1Instance.Value and someType2Instance.Value without caring what the concreate type it is and without caring what the return type is (I can use object).
So my code is currently:
public interface ISomeType<V>
{
V Value {get; set;}
}
public interface ISomeTypeWrapper
{
object Value { get; set; }
}
public class SomeTypeWrapper<T> : ISomeTypeWrapper
where T : ISomeType<???>
{
T someType;
public SomeTypeWrapper(T wrappedSomeType)
{
someType = wrappedSomeType
}
public object Value
{
get { return someType.Value; }
set { someType.Value = value != null ? value : default(T); }
}
}
public class SomeType1
{
public int Value { get; set; }
}
public class SomeType2
{
public string Value { get; set; }
}
The problem is that I don't know what T might be until runtime due to the fact that I get a dictionary of objects.
I can iterate the dictionary and use reflection to create a SomeWrapperType on runtime but I would like to avoid it.
How can I mixin the concreate type of SomeType to ISomeType?
How can I know what V type parameter is? (wish I had typedefs and decltype like in c++)
How can I, with the minimum of use of reflection possible Mixin those classes with the interface/base class?
You could try the Duck Typing Extensions for Windsor. It means you will need to register each of your types.
container
.Register(Component.For(typeof(SomeType1)).Duck<ISomeType>())
.Register(Component.For(typeof(SomeType2)).Duck<ISomeType>());
You could probably use linq and the register AllTypes syntax to reduce code if the names are similar.
Alternatively in the short term create a factory which can return you the objects you need, implement a concrete object for each type. No you are using the interface you can remove the factory at a later date and replace it with something else with minimal impact:
public class SomeTypeWrapperFactory
{
public ISomeType<int> CreateWrapper(SomeType1 someType1)
{
return new SomeType1Wrapper(someType1);
}
public ISomeType<string> CreateWrapper(SomeType2 someType2)
{
return new SomeType2Wrapper(someType2);
}
}
public class SomeType1Wrapper : ISomeType<int> { ... }
public class SomeType2Wrapper : ISomeType<int> { ... }
Regardless of how you implement the wrapper, be the individually or using a god like class you have the ability to change how the wrapping is done and keep the rest of your code clean.
Why SomeTypeWrapper but not SomeObjectWrapper?
public class SomeObjectWrapper : ISomeType
{
Object _someObject;
PropertyInfo _valuePropertyInfo;
public SomeObjectWrapper(Object wrappedSomeObject)
{
_someObject = wrappedSomeObject;
_valuePropertyInfo = _someObject.GetType().GetProperty("Value", System.Reflection.BindingFlags.Public);
}
public object Value
{
get { return _valuePropertyInfo.GetValue(_someObject, null); }
set { _valuePropertyInfo.SetValue(_someObject, value, null); }
}
}
Edited With .NET 3.5 using LinFu
You may use LinFu instead of Castle. However, you would be using reflection anyway, both with Castle's and with Linfu's DynamicProxy, only hidden in the guts of the libraries instead of being exposed in your code. So if your requirement to avoid the use of reflection is out of performance concerns, you wouldn't really avoid it with this solution.
In that case I would personally choose Orsol's solution.
However: here's an example with LinFu's ducktyping.
public interface ISomeType {
object Value{get; set;}
}
public class SomeType1
{
public int Value { get; set; }
}
public class SomeType2
{
public string Value { get; set; }
}
public class SomeTypeWrapperFactory
{
public static ISomeType CreateSomeTypeWrapper(object aSomeType)
{
return aSomeType.CreateDuck<ISomeType>();
}
}
class Program
{
public static void Main(string[] args)
{
var someTypes = new object[] {
new SomeType1() {Value=1},
new SomeType2() {Value="test"}
};
foreach(var o in someTypes)
{
Console.WriteLine(SomeTypeWrapperFactory.CreateSomeTypeWrapper(o).Value);
}
Console.ReadLine();
}
}
Since you don't know the type of the SomeType's until runtime, I would not use mixins, but the visitor pattern (I know this doesn't answer the question on how to use mixins for this, but I just thought I'd throw in my 2 cents).
With .NET 4 using dynamic
See Bradley Grainger's post here on using c#4's dynamic keyword to implement the visitor pattern.
In your case, reading all the "Value" properties from your dictionary of SomeType's could work like this:
public class SomeType1
{
public int Value { get; set; }
}
public class SomeType2
{
public string Value { get; set; }
}
public class SomeTypeVisitor
{
public void VisitAll(object[] someTypes)
{
foreach(var o in someTypes) {
// this should be in a try-catch block
Console.WriteLine(((dynamic) o).Value);
}
}
}
class Program
{
public static void Main(string[] args)
{
var someTypes = new object[] {
new SomeType1() {Value=1},
new SomeType2() {Value="test"}
};
var vis = new SomeTypeVisitor();
vis.VisitAll(someTypes);
}
}
I have an interface named IHarvester.
There are 3 implementations of that interface, each under their own namespace:
Google
Yahoo
Bing
A HarvesterManager uses the given harvester. It knows the interface and all 3 implementations.
I want some way of letting the class user say in which harvester it wants to use. And in the code select that implementation, without a switch-case implementation.
Can reflection save my day?
Here is the code bits:
// repeat for each harvester
namespace Harvester.Google
{
public abstract class Fetcher : BaseHarvester, IInfoHarvester {...}
}
public enum HarvestingSource
{
Google,
Yahoo,
Bing,
}
class HarvesterManager {
public HarvestingSource PreferedSource {get;set;}
public HarvestSomthing()
{
switch (PreferedSource) .... // awful...
}
}
Thanks.
I will give my 2 cents of why I want to change this. There several people writing harvesters, I want them to focus only on building more harvesters, without ever needing to update the enum, or at worst, update only the enum.
I think you should look on dependency injection. You could use exising IoC containers instead of inventing your own one, e.g. you could use Unity. Here is an article on how you could use Unity.
Since they're all inheriting from a common interface, you can use Activator to create an instance of an object using that interface, but all that will be available to you would be the specific properties and methods of the interface. Something like the below.
using System;
using Demo;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Type type = Type.GetType("Harvester.Google.GoogleHarvester");
IHarvester harvester = (IHarvester)Activator.CreateInstance(type);
Console.WriteLine(harvester.Blah);
Console.Read();
}
}
public interface IHarvester
{
string Blah { get; }
}
}
namespace Harvester.Google
{
public class GoogleHarvester : IHarvester
{
#region IHarvester Members
public string Blah
{
get
{
return "Google";
}
}
#endregion
}
}
namespace Harvester.Yahoo
{
public class YahooHarvester : IHarvester
{
#region IHarvester Members
public string Blah
{
get { return "Yahoo"; }
}
#endregion
}
}
namespace Harvester.Bing
{
public class BingHarvester : IHarvester
{
#region IHarvester Members
public string Blah
{
get { return "Bing"; }
}
#endregion
}
}
I think you would get more milage from a Strategy Pattern implemenation.
If you have a fixed set of options to choose from I'd go for the factory class:
internal static class HarvestorFactory
{
private static Dictionary<HarvestingSource, IHarvester> harvesters =
new Dictionary<HarvestingSource, IHarvester>
{
{ HarvestingSource.Google, new GoogleHarvester() },
{ HarvestingSource.Yahoo, new YahooHarvester() },
{ HarvestingSource.Bing, new BingHarvester() },
};
internal static IHarvester Get( HarvestingSource source )
{
return harvesters[ source ];
}
}
This gives you freedom to control whether instances should be singletons (as in the example above), per-caller or some other option that fits the scenario in which the code is used.
I have been getting a lot of traction from a builder pattern as a public class member of another class:
public class Part
{
public class Builder
{
public string Name { get; set; }
public int Type { get; set; }
public Part Build()
{
return new Part(Name, Type);
}
}
protected Part(string name, int type)
{
...
}
}
Note protected constructor - I like how I HAVE to use the builder to get a Part. Calls to
Part p = new Part.Builder() { Name = "one", Type = 1 }.Build();
work great. What I would like to do is use this builder to serve up a special kind of part based on the Type (for example):
public class SpecialPart : Part
{
protected SpecialPart(string name, int type) : base(name, type) { }
}
And a slight change to the builder:
public Part Build()
{
if (Type == _some_number_)
return new SpecialPart(Name, Type);
return new Part(Name, Type);
}
But this doesn't work - Part.Builder can't see SpecialPart's protected constructor. How can I get Builder to work with descendents of Part and get the same must-have-a-builder semantics?
There are many ways to skin a cat, but the path of least resistance here is going to be making the constructors of your various part types public or internal.
You can't do it, except for putting them in their own assembly and use the internal access specifier.