How should I choose an instance of an AbstractFactory? - c#

Currently I'm having a trouble with instantiating an AbstractFactory. There are some classes:
abstract class ABase { }
class A1 : ABase { }
class A2 : ABase { }
abstract class BBase { }
class B1 : BBase
{
private readonly A1 _a;
public B1(A1 a)
{
_a = a;
}
}
class B2 : BBase
{
private readonly A2 _a;
public B2(A2 a)
{
_a = a;
}
}
abstract class FactoryBBase
{
abstract public BBase Create(ABase b);
}
class FactoryB1 : FactoryBBase
{
override public BBase Create(ABase b)
{
return new B1(b as A1);
}
}
class FactoryB2 : FactoryBBase
{
override public BBase Create(ABase b)
{
return new B2(b as A2);
}
}
class Runtime
{
public void ProcessA(ABase a)
{
//How should I choose a proper factory?
}
}
How do I instantiate a proper abstract factory in ProcessA method depending on the type of a? The thing is that I don't want to have a big if/else block.

how to instantiate a proper abstract factory in ProcessA method depending on the type of a?
To avoid big if/else block you can put all factories into a map, where key is the type of a and value is the implementation. in Java I would do this either by Spring or I would create a static code, that can initialize the map when the class is loaded.
do I use AbstractFactory pattern as it is supposed to be uesd?
IMHO yes.

You can use a lookup dictionary instead of a if-else/switch construct.
//classes used as markers
public interface IMarker {}
public class MarkerA : IMarker {}
public class MarkerB : IMarker {}
//classes to be created
public interface IData {}
public class DataA : IData {}
public class DataB : IData {}
//factory to call abstract factories (could use static here)
public class Factory
{
public IData Create(IMarker marker)
{
//lookup dictionary instead of if/switch
//func ensures instance is only created when required
var lookup = new Dictionary<Type, Func<DataFactoryBase>>()
{
{ typeof(MarkerA), () => new DataAFactory() },
{ typeof(MarkerB), () => new DataBFactory() },
};
//get factory by type and call constructor
return lookup[marker.GetType()]().Create();
}
}
//abstract factories
public abstract class DataFactoryBase
{
public abstract IData Create();
}
public class DataAFactory : DataFactoryBase
{
public override IData Create()
{
return new DataA();
}
}
public class DataBFactory : DataFactoryBase
{
public override IData Create()
{
return new DataB();
}
}
public static void Main()
{
//example will return DataA
IData data = new Factory().Create(new MarkerA());
}

How to implement abstract factory really depends on what you need. What you have there is indeed a proper implementation, but I think it's not exactly what you need since you want to do something differently dependending on the type or state of an instance of ABase.
The logic that analyses the type or state is exactly what I'd put into a factory.
abstract class ABase { }
class A1 : ABase { }
class A2 : ABase { }
public abstract class FactoryBBase
{
public abstract IProcessor Create(ABase a);
}
public class ConcreteFactory : FactoryBBase
{
override public IProcessor Create(ABase a)
{
// this is ugly for a large amount of ABase implementations of course
if (a is A1)
{
return new Runtime1();
}
if (a is A2)
{
return new Runtime2();
}
throw new NotSupportedException();
}
}
public interface IProcessor
{
void ProcessA(ABase a);
}
public class Runtime1 : IProcessor
{
public void ProcessA(ABase a)
{
// process away
}
}
public class Runtime2 : IProcessor
{
public void ProcessA(ABase a)
{
// process away differently
}
}
Multiple factory implementations come into play when you want the same type of ABase implementation to be processed by different types of Runtime/Processor depending on state that is outside of ABase.

Related

Creational pattern for generic objects

could someone please help with the best way of returning the concrete implementation in the following scenarios. Say I have:
public interface IThing<TInput> where TInput : RequestBase
{
string Process(T input);
}
And then multiple implementations:
public class Thing1<T> : IThing<T> where T : ReqThing1
public class Thing2<T> : IThing<T> where T : ReqThing2
In my calling class what is the best way of wrapping the construction of those classes and returning the IThing that I want in a clean, testable way? Thanks
I don't quite understand what you want, but here's an idea:
public abstract class RequestBase
{
}
public class ReqThing1 : RequestBase
{
}
public class ReqThing2 : RequestBase
{
}
public interface IThing<T> where T : RequestBase
{
string Process(T input);
}
public class Thing1 : IThing<ReqThing1>
{
public string Process(ReqThing1 input)
{
throw new System.NotImplementedException();
}
}
public class Thing2 : IThing<ReqThing2>
{
public string Process(ReqThing2 input)
{
throw new System.NotImplementedException();
}
}
public class Program
{
public static void Main(string[] args)
{
var thing1 = new Thing1();
var thing2 = new Thing2();
}
}

How to hide a member function when the base class uses generics

I have the following classes, and when I call CreateQuerySettings on the BaseScriptConfigurationList, it returns the new QuerySettings from ConfigurationList, rather than the HierarchicalQuerySettings value in BaseScriptConfigurationList:
public abstract class ConfigurationList<TConfigurationObject, TPropertyEnum>
{
public QuerySettings<TConfigurationObject, TPropertyEnum> CreateQuerySettings()
{
return new QuerySettings<TConfigurationObject, TPropertyEnum>();
}
}
public class BaseScriptConfigurationList : EditableConfigurationList<BaseScriptConfiguration, BaseScriptConfiguration.Property>
{
public BaseScriptConfigurationList(ConfigurationManager configurationManager)
: base(configurationManager, InternalAdminObjectType.BaseScript)
{
_BaseScriptPageListWatcher = new ConfigurationList<BaseScriptPageConfiguration, BaseScriptPageConfiguration.Property>.
ConfigurationWatcher(null);
_ConfigurationWatcher.ChildWatchers.Add(_BaseScriptPageListWatcher);
}
public new QuerySettings<BaseScriptConfiguration, BaseScriptConfiguration.Property> CreateQuerySettings()
{
return new HierarchicalQuerySettings<BaseScriptConfiguration, BaseScriptConfiguration.Property, BaseScriptQueryChildrenSettings>();
}
}
Edit: I make the call from another class where TConfigurationObjectList is BaseScriptConfigurationList. I've added the constructor to the code above so you can see what it's doing. Please note that EditableConfigurationList inherits from ConfigurationList.
TConfigurationObjectList cl = (TConfigurationObjectList)typeof(TConfigurationObjectList).GetConstructor(new Type[] { typeof(ConfigurationManager) }).Invoke(new object[] { Manager.ConfigurationManager });
var querySettings = cl.CreateQuerySettings();
When I make this call, it goes into the ConfigurationList.CreateQuerySettings method.
How can I hide the CreateQuerySettings method, so that when I call it from the BaseScriptConfigurationList class, I get a HierarchicalQuerySettings object?
The new modifier can be beasty. Note that you are hiding and not overriding in your example. You are not showing that part of the code, but I assume you have this situation:
class Base
{
public static void BaseMethod() { Console.WriteLine("BASE!"); }
}
class Derived : Base
{
// Hides Base.BaseMethod()
new public static void BaseMethod() { Console.WriteLine("DERIVED!"); }
}
Base a = new Base();
a.BaseMethod(); // -> "BASE!"
Base b = new Derived();
b.BaseMethod(); // -> "BASE!"
Derived b = new Derived();
b.BaseMethod(); // -> "DERIVED!"
In BaseScriptConfigurationList.CreateQuerySettings()
you're return type is QuerySettings<T,T> so you will always get that type as a return value, but you are returning a HierarchicalQuerySettings. You can one, change the return type of CreateQuerySettings() to HierarchicalQuerySettings or two, cast the object to its child type "HierarchicalQuerySettings". If you really want to hide it, you can do this:
public class newclass : BaseScriptConfigurationList
{
public new HierarchicalQuerySettings<BaseScriptConfiguration, BaseScriptConfiguration.Property> CreateQuerySettings()
{
return (HierarchicalQuerySettings<BaseScriptConfiguration, BaseScriptConfiguration.Property>)base.CreateQuerySettings();
}
}
But that doesn't really seem efficient and i advise against it. Like i said, i maybe missing some other requirement, but based on the info that you gave..
Basically, what I'm seeing (and making assumptions) that TConfigurationObjectList Inhertis from ConfigurationList somewhere along the lines, so on and so forth, all the way up to EditableConfigurationList. since you are dynamically creating an instance of the class TConfigurationObjectList, and calling the method from that point, you will be calling the base ConfigurationList member CreateQuerySettings. You do not have access to the new CreateQuerySettings. If you are creating the class BaseScriptConfigurationList instance at this point, cast the object ((BaseScriptConfigurationList)cl).CreateQuerySettings(). That being said. if you do not know what you have at runtime:
var obj = typeof(TConfigurationObjectList).GetConstructor(new Type[] { typeof(ConfigurationManager) }).Invoke(new object[] { Manager.ConfigurationManager });
var cl = (obj as BaseScriptConfigurationList) ?? (TConfigurationObjectList)obj;
// or do something else
var querySettings = cl.CreateQuerySettings();
Note i am assuming your architecture is roughly set up like this:
public abstract class ConfigurationList<TConfigurationObject, TPropertyEnum>
{
public QuerySettings<TConfigurationObject, TPropertyEnum> CreateQuerySettings()
{
return new QuerySettings<TConfigurationObject, TPropertyEnum>();
}
}
public class TConfigurationObjectList : ConfigurationList<BaseScriptConfiguration, BaseScriptConfiguration.Property>
{
}
public class EditableConfigurationList<T, T1> : TConfigurationObjectList
{
protected EditableConfigurationList(ConfigurationManager configurationManager, object baseScript)
{
throw new NotImplementedException();
}
}
public class BaseScriptConfigurationList : EditableConfigurationList<BaseScriptConfiguration, BaseScriptConfiguration.Property>
{
public BaseScriptConfigurationList(ConfigurationManager configurationManager)
: base(configurationManager, InternalAdminObjectType.BaseScript)
{
}
public new QuerySettings<BaseScriptConfiguration, BaseScriptConfiguration.Property> CreateQuerySettings()
{
return new HierarchicalQuerySettings<BaseScriptConfiguration, BaseScriptConfiguration.Property, BaseScriptQueryChildrenSettings>();
}
}
public class QuerySettings<T, T1>
{
}
public class HierarchicalQuerySettings<T, T1, T2> : QuerySettings<BaseScriptConfiguration, BaseScriptConfiguration.Property>
{
}
public class BaseScriptQueryChildrenSettings
{
}
public class BaseScriptPageConfiguration
{
public class Property
{
}
}
public class InternalAdminObjectType
{
public static object BaseScript { get; set; }
}
public class ConfigurationManager
{
}
public class BaseScriptConfiguration
{
public class Property
{
}
}
Create a base interface for the ConfigurationList class (say IConfigurationList) and use this interface as the data type for the variable cl instead of TConfigurationList.

How to return child types from a static generic property

I want to have a base class:
public class Base
{
public static T Instance
{
get
{
// do something to return new instance of inherit class from itself
}
}
}
Class1:
public class Class1 : Base
{
// method and properties here
public string Func1()
{
return 'class1';
}
}
Class2:
public class Class2 : Base
{
// method and properties here
public string Func1()
{
return 'class2';
}
}
I want it so that we can use Class1 or Class2 like this
public class Main
{
var a = Base<Class1>.Instance.Func1(); // return 'class1'
var b = Base<Class2>.Instance.Func1(); // return 'class2'
}
Please help me to do this.
This is not called dynamic but polymorphic. In this case achieved with generics. Your only remaining problem is calling the constructor, which becomes possible when you put a Type-constraint on <T>.
public class Base<T> where T : new()
{
public static T Instance
{
get
{
// do something to return new instance of inherit class from itself
return new T();
}
}
}
and then:
public class Class1 : Base<Class1> { ... }
public class Class2 : Base<Class2> { ... }
But note that a simpler solution could be achieved with virtual+override methods or with an interface.
Alternative suggestion with some tighter type constraints:
namespace My.Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Base<Class1>.Instance.Func1());
Console.WriteLine(Base<Class2>.Instance.Func1());
}
}
public abstract class Base
{
public abstract string Func1();
}
public sealed class Base<T> where T : Base, new()
{
public static T Instance
{
get { return new T(); }
}
}
public class Class1 : Base
{
public override string Func1() { return "class 1"; }
}
public class Class2 : Base
{
public override string Func1() { return "class 2"; }
}
}

Controlling read/write access to fields

Suppose that we would like to separate out the read and write access in an interface pattern as below.
namespace accesspattern
{
namespace ReadOnly
{
public interface IA { double get_a(); }
}
namespace Writable
{
public interface IA : ReadOnly.IA { void set_a(double value); }
}
}
This is easy to implement:
namespace accesspattern
{
namespace ReadOnly
{
public class A : IA
{
protected double a;
public double get_a() { return a; }
}
}
namespace Writable
{
public class A : ReadOnly.A, IA
{
public void set_a(double value) { base.a = value; }
}
}
}
Suppose that we need another class which inherits from A and so we go ahead and define an interface for it:
namespace accesspattern
{
namespace ReadOnly
{
public interface IB : ReadOnly.IA { int get_b(); }
}
namespace Writable
{
public interface IB : ReadOnly.IB, Writable.IA { void set_b(int value); }
}
}
Implementing this is not so easy. One always feels that Writable.B should inherit from two base classes, Writable.A and ReadOnly.B, to avoid repeated code.
Is there a recommended Design Pattern to use? The aim is to be able to return "read access only" and "read write access" objects separately (decided at compile time) depending on requirements. It would be nice if the solution pattern makes it easy to add more layers of inheritance, classes C, D...
I know that the issue of Multiple Inheritance crops up here and that it has been discussed at length elsewhere in many, many, places. But my question is not so much "How to implement the interfaces which are defined inside the namespace accesspattern without using multiple inheritance" (although I would like to learn the best way to do that) but rather, how can we define the ReadOnly/Writable versions of a class separately and also support inheritance without it getting very, very, messy?
For what it is worth here is one (messy) solution [see below for much a better implementation]:
namespace accesspattern
{
namespace ReadOnly
{
public class A : IA
{
protected double a;
public double get_a() { return a; }
}
public class B : IB
{
protected int b;
public int get_b() { return b; }
}
}
namespace Writable
{
public class A : ReadOnly.A, IA
{
public void set_a(double value) { base.a = value; }
}
public class B : ReadOnly.B, IB
{
private IA aObj;
public double get_a() { return aObj.get_a(); }
public void set_a(double value) { aObj.set_a(value); }
public void set_b(int value) { base.b = value; }
public B() { aObj = new A(); }
}
}
}
}
Update: I think that this (below) is what Eugene is talking about. This implementation pattern is pretty good, I think. By only passing around "writeProtected" views of classes one can implement algorithms which require that the state of the class will not change and only use "writeEnabled" views where it is meant that the function will/could cause a change in state avoiding.
namespace access
{
// usual usage is at least readable
public interface IA { double get_a(); }
public interface IB : IA { int get_b(); }
// special usage is writable as well
namespace writable
{
public interface IA : access.IA { void set_a(double value); }
public interface IB : access.IB, IA { void set_b(int value);}
}
// Implement the whole of A in one place
public class A : writable.IA
{
private double a;
public double get_a() { return a; }
public void set_a(double value) { a = value; }
public A() { }
//support write-protection
public static IA writeProtected() { return new A(); }
public static writable.IA writable() { return new A(); }
}
// implement the whole of B in one place and now no issue with using A as a base class
public class B : A, writable.IB
{
private int b;
public double get_b() { return b; }
public void set_b(int value) { b = value; }
public B() : base() { }
// support write protection
public static IB writeProtected() { return new B(); }
public static writable.IB writable() { return new B(); }
}
public static class Test
{
static void doSomething(IA a)
{
// a is read-only
}
static void alterState(writable.IB b)
{
// b is writable
}
static void example()
{
// Write protected
IA a = access.A.writeProtected();
IB b = access.B.writeProtected();
// write enabled
writable.IA A = access.A.writable();
writable.IB B = access.B.writable();
Console.WriteLine(a.get_a());
B.set_b(68);
doSomething(A); // passed as writeprotected
alterState(B); // passed as writable
}
}
}
I know this thread is one year old, but I'm wondering if it would make sense to have something like this:
interface ReadOnlyA
{
object A { get; }
}
interface WriteableA : ReadOnlyA
{
new object A {get; set;}
}
You can provide the read/write access at Service level and not at Entity level. In that case you can code generate a wrapper around services that handles the read/write access.
Patterns used: Decorator, Dependency Injection

How do you implement constructor injection in a factory?

When you're using a factory pattern, how do you inject dependencies into constructors at runtime?
I'm building Foos with different formats - boolean, array, freetext, matrix, etc. That format list will grow as we find different uses for Foo. Here's my basic core domain:
public interface IFoo
{
FooFormat Format { get; }
}
public class Foo : IFoo
{
private FooFormat _format;
internal Foo(FooFormat format)
{
_format = format;
}
public FooFormat Format { get { return _format; } }
}
public abstract class FooFormat
{
}
public class DefaultFooFormat : FooFormat
{
}
public class BooleanFooFormat : FooFormat
{
public IList<bool> Values { get; set; }
}
public class ArrayFooFormat : FooFormat
{
private IList<string> _values;
public ArrayFooFormat(IList<string> values)
{
_values = values;
}
public IList<string> Values { get { return _values; } }
}
IFoo is decorated for the consumer context:
public abstract class FooDecorator : IFoo
{
private IFoo _foo;
protected FooDecorator(IFoo foo)
{
_foo = foo;
}
public FooFormat Format
{
get { return _foo.Format; }
}
protected IFoo foo
{
get { return _foo; }
}
}
I don't want my consumer to instantiate a Foo directly, so I force them to use a factory:
public abstract class FooFactory
{
protected IFoo Build<T>()
{
FooFormat format = GetFormat<T>();
return new Foo(format);
}
private FooFormat GetFormat<T>()
{
if (typeof(T) == typeof(ArrayFooFormat)) return new ArrayFooFormat(new List<string>());
if (typeof(T) == typeof(BooleanFooFormat)) return new BooleanFooFormat();
return new DefaultFooFormat();
}
}
And even then, they need to derive a factory from my abstract factory for their particular context.
I'm specifically building foos in an html context, like so:
public class HtmlFoo : FooDecorator
{
public HtmlFoo(IFoo foo) : base(foo) { }
public string ToHtml()
{
return "<div>" + this.Format.ToString() + "</div>";
}
}
public class HtmlFooFactory : FooFactory
{
public IFoo BuildFoo<T>()
{
IFoo foo = Build<T>();
return new HtmlFoo(foo);
}
}
public class HtmlFooConsumer
{
public void DoSomeFoo()
{
var factory = new HtmlFooFactory();
var htmlBooleanFoo = factory.BuildFoo<BooleanFooFormat>();
var htmlArrayFoo = factory.BuildFoo<ArrayFooFormat>();
}
}
My problem is in my abstract FooFactory: I'm always injecting an empty value list into my ArrayFooFormat. I want to be able to pass in a value list from the consumer. For other FooFormats, I want to pass in the right constructor arguments from the consumer. But I want to keep the public API dead simple - I don't want a bunch of overloads on BuildFoo().
So how do I pass a custom value list into the factory.BuildFoo<T>() call from inside HtmlFooConsumer.DoSomeFoo()? Any ideas, stackoverflow gurus?
Maybe you can do something along these lines where your abstract FooFormat becomes IFooFormat and a generic FooFormat provides an Init method that gets passed the parameter.
Then a single overload of Build lets you pass in the parameter.
public interface IFooFormat
{
}
public class FooFormat<TValue> : IFooFormat
{
private TValue _value;
public void Init(TValue value)
{
_value = value;
}
public TValue Value
{
get { return _value; }
}
}
public class ArrayFooFormat : FooFormat<IList<string>> { }
public class BooleanFooFormat : FooFormat<bool> { }
public class DefaultFooFormat : IFooFormat { }
public interface IFoo { }
public class Foo : IFoo
{
private IFooFormat _format;
internal Foo(IFooFormat format)
{
_format = format;
}
public IFooFormat Format { get { return _format; } }
}
public class FooFactory
{
protected IFoo Build<TFormat, TArg>(TArg arg) where TFormat : FooFormat<TArg>, new()
{
TFormat format = new TFormat();
format.Init(arg);
return new Foo(format);
}
protected IFoo Build<TFormat>() where TFormat : IFooFormat, new()
{
return new Foo(new TFormat());
}
}
A factory is basically the object oriented version of a static variable. I'd avoid using one alltogether. Instead of forcing clients to use a factory, perhaps you can simply inject objects into their constructors, sidestepping the need for a factory.

Categories