Let's say, I have a list of strategies which are presented as interfaces and a class (Container) which implements these strategies explicitly. Now I want a method to perform one of these strategies as it's specified in the generic type parameter. The question is in the code.
interface IStrategy
{
void PerformAction();
}
interface IChasingStrategy : IStrategy
{
new void PerformAction();
}
interface ITestStrategy : IStrategy
{
new void PerformAction();
}
class Container : IChasingStrategy, ITestStrategy
{
void IChasingStrategy.PerformAction()
{
Console.WriteLine("ChasingStrategy");
}
void IStrategy.PerformAction()
{
Console.WriteLine("Strategy");
}
void ITestStrategy.PerformAction()
{
Console.WriteLine("TestStrategy");
}
}
class Program
{
static void PerformStrategy<TStrategy>(Container container) where TStrategy : IStrategy
{
TStrategy strategy = container; //why can't I use here implicit casting?
//However this is valid:
//IStrategy strat = container;
//IChasingStrategy ch_strat = container;
//ITestStrategy ts_strat = container;
strategy.PerformAction();
}
static void Main(string[] args)
{
var container = new Container();
PerformStrategy<IChasingStrategy>(container);
}
}
You can let it decide at runtume, which Strategy should it run by the following code.
class Container<T> Where T : IStrategy
{
public void ActionFactory()
{
T.PerformAction();
}
.
.
.
}
And in the Program class:
static void PerformStrategy<TStrategy>(Container<TStrategy> container) where TStrategy : IStrategy
{
container.ActionFactory(); //to perform the desired action for your strategy
}
When you calling the PerformStrategy method, you can decide what container should it get by:
PerformStrategy(new Container<IChasingStrategy>);
You can take off the class binding by making the ActionFactory method generic.
class Container
{
public void ActionFactory<T>() where T: IStrategy
{
T.PerformAction();
}
.
.
.
}
class Program
{
static void PerformStrategy<TStrategy>(Container container) where T: IStrategy
{
container.ActionFactory<TStrategy>(); //to perform the desired action for your strategy
}
}
PerformStrategy<IChasingStrategy>(new Container());
Related
I have a number of methods that are called on different 3rd party systems. I now have another 3rd party system that will have the same set of methods actioned against it. If both 3rd party systems are connected I will then call the methods on each object in turn.
Currently I have a class that I pass round that I can call the method once and it checks and then calls it on each system that is enabled, this has an instance of each objects classes, similar to this:
public class AACSCaller
{
3rdPartySystem1 _system1;
3rdPartySystem2 _system2;
public AACSCaller(Settings appSettings)
{
_appSettings = appSettings;
if (appSettings.system1Enabled)
{
_system1 = new 3rdPartySystem1();
}
if (appSettings.system2Enabled)
{
_system2 = new 3rdPartySystem2();
}
}
public void Method1()
{
if (appSettings.system1Enabled)
{
_system1.Method1();
}
if (appSettings.system2Enabled)
{
_system2.Method1();
}
}
public void Method2()
{
if (appSettings.system1Enabled)
{
_system1.Method2();
}
if (appSettings.system2Enabled)
{
_system2.Method2();
}
}
}
Is this sensible, as it does seem there maybe a better way and I may well be connecting additional system at some point.
A possible solution here is to define an interface or base class for 3rdPartySystem1 and 3rdPartySystem2 classes, store instances in a collection and call required methods for every item in collection. If only one system is enabled, you'll have only one item in collection, if both is enabled, you'll call them one by one in loop
public interface IThirdPartySystem
{
void Method1();
void Method2();
}
public class ThirdPartySystem1 : IThirdPartySystem
{
//implementation
}
public class ThirdPartySystem2 : IThirdPartySystem
{
//implementation
}
public class AACSCaller
{
IList<IThirdPartySystem> _systems = new List<IThirdPartySystem>();
public AACSCaller(Settings appSettings)
{
_appSettings = appSettings;
if (appSettings.system1Enabled)
{
_systems.Add(new ThirdPartySystem1());
}
if (appSettings.system2Enabled)
{
_systems.Add(new ThirdPartySystem2());
}
}
public void Method1()
{
foreach (var system in _systems)
system.Method1();
}
public void Method2()
{
foreach (var system in _systems)
system.Method2();
}
}
I suggest you to use interface that have Method1 and Method2 methods and then create to classes System1 and System2 that are implements the interface. Where AACSCaller is create you initialize the correct implementation of the interface and in your methods your just Call to the correct instance method without conditions.
public class AACSCaller
{
IThirdPartySystem ThirdPartySystem;
public AACSCaller(Settings appSettings)
{
_appSettings = appSettings;
ThirdPartySystem = appSettings.system1Enabled ? new ThirdPartySystem1() : new ThirdPartySystem2();
}
public void Method1() => ThirdPartySystem.Method1();
public void Method2() => ThirdPartySystem.Method2();
}
public interface IThirdPartySystem
{
void Method1();
void Method2();
}
public class ThirdPartySystem1 : IThirdPartySystem
{
public void Method1()
{
//code here..
}
public void Method2()
{
//code here..
}
}
public class ThirdPartySystem2 : IThirdPartySystem
{
public void Method1()
{
//code here..
}
public void Method2()
{
//code here..
}
}
Probably a bad title, but I am trying to abstract away the type "EventHub" from my generic Handler class.
I would like to inject a function instead into my subscribe method to decouple the two types. Unfortunately, the only way I can see doing this is if I make my IHandler a generic, but this causes other problems.
Is there a design pattern to decouple these two types? Commented out are lines that I would like in some way.
public interface IHandler
{
//void Subscribe(Func<Action<T>, Guid> subscribe);
void Subscribe(EventHub eventHub);
void Unsubscribe(Action<Guid> action);
}
public abstract class Handler<T> : IHandler
{
private Guid _subscriptionToken;
public virtual void Subscribe(EventHub eventHub)
{
var action = new Action<T>(Handle);
_subscriptionToken = eventHub.Subscribe(action);
}
/*public virtual void Subscribe(Func<Action<T>, Guid> subscribe)
{
var action = new Action<T>(Handle);
_subscriptionToken = subscribe(action);
}*/
public virtual void Unsubscribe(Action<Guid> action)
{
action(_subscriptionToken);
}
public abstract void Handle(T eventType);
}
Thanks for the help!
internal interface IHandler
{
void Subscribe(Func<Action<object>, Guid> subscribe);
void Unsubscribe(Action<Guid> action);
}
public abstract class Handler<T> : IHandler
{
private Guid _subscriptionToken;
public virtual void Subscribe(Func<Action<object>, Guid> subscribe)
{
var action = new Action<T>(HandleNonAsync);
_subscriptionToken = subscribe(Convert(action));
}
public virtual void Unsubscribe(Action<Guid> action)
{
action(_subscriptionToken);
}
public abstract Task HandleAsync(T eventType);
private void HandleNonAsync(T eventType)
{
HandleAsync(eventType).GetAwaiter().GetResult();
}
private Action<object> Convert(Action<T> myActionT)
{
if (myActionT == null) return null;
else return new Action<object>(o => myActionT((T)o));
}
}
I have the following situation.
SomeClass has a dependency on IDiagram and Diagram implements that interface. The lifetime of SomeClass is the lifetime of the Application, however the lifetime a Diagram is shorter. Say it could change when a certain button is pressed.
Since I could not find anything satisfying on this problem I came up with the pattern depicted in the Diagram below.
The Observer of the Diagram would be aware that the Diagram can change and set the correct instance when it changes.
The Observer would implement the IDiagram interface by delegating the methods of the current Diagram instance.
SomeFactory would create new Diagrams and RaiseChanged.
SomeClass would not be aware of any of this.
Is enforcing this pattern a good idea, which downsides are there? Is there a better solution to this problem?
Example code with IDependency instead of IDiagram below:
private static void Main(string[] args)
{
var transientDependency = new TransientDependency();
var dependencyObserver = new DependecyObserver(transientDependency);
var dependencyFactory = new Factory(transientDependency);
var someClass = new SomeClass(dependencyObserver);
var someOtherClass = new SomeClass(dependencyObserver);
// Note that someClass can only be used after the dependency has been created, because the Changed event has to be invoked
dependencyFactory.CreateDependency();
}
public class DependecyObserver : IDependency
{
public DependecyObserver(TransientDependency transient)
{
transient.Changed += (s, dependency) => Dependency = dependency;
}
private Dependency Dependency { get; set; }
public void SomeMethod()
{
Dependency.SomeMethod();
}
}
public class Factory
{
private TransientDependency TransientDependency { get; }
public Factory(TransientDependency transientDependency)
{
TransientDependency = transientDependency;
}
public void CreateDependency()
{
TransientDependency.RaiseChanged(new Dependency());
}
}
public class SomeClass
{
public SomeClass(IDependency dependency)
{
dependency.SomeMethod();
}
}
public class TransientDependency : TransientInstance<Dependency> { }
public abstract class TransientInstance<T>
{
public EventHandler<T> Changed;
public void RaiseChanged(T instance)
{
Changed?.Invoke(this, instance);
}
}
public class Dependency : IDependency
{
public void SomeMethod()
{
throw new NotImplementedException();
}
}
public interface IDependency
{
void SomeMethod();
}
I have an interface IInterface and it looks something like below -
public interface IInterface
{
void SomeMethod1();
void SomeMethod2();
void SomeMethod3();
.
.
.
}
One of the implementations is something like -
public class Implementation : IInterface
{
private Object obj;
public Implementation(Object obj)
{
this.obj = obj;
// Do Something
}
public void SomeMethod1()
{
lock(obj)
{
// Do Something
}
}
public void SomeMethod2()
{
// Do Something
}
public void SomeMethod3()
{
lock(obj)
{
// Do Something
}
}
.
.
.
}
How to pass a static readonly instance of type Object while registering Implementation class with type IInterface via unity configuration?
My preferred approach is probably to create a factory for creating IInterfaces
public interface IInterface
{
void SomeMethod1();
}
public interface IInterfaceFactory
{
IInterface CreateInterface();
}
public class StandardInterfaceFactory : IInterfaceFactory
{
// Define your static lock object here. Other customers
// can define their own IInterfaceFactory to use a
// different lock object.
private static readonly object lockObject = new object();
public IInterface CreateInterface()
{
return new StandardInterface(lockObject);
}
}
public class StandardInterface : IInterface
{
private readonly object lockObject;
public StandardInterface(object lockObject)
{
this.lockObject = lockObject;
}
public void SomeMethod1()
{
lock (this.lockObject)
{
Console.WriteLine("I've locked on " + lockObject);
}
}
}
Your unity configuration and client code will then look like this.
void Main()
{
IUnityContainer container = new UnityContainer();
// This mapping can be done trivially in XML configuration.
// Left as an exercise for the reader :)
container.RegisterType<IInterfaceFactory, StandardInterfaceFactory>();
IInterfaceFactory factory = container.Resolve<IInterfaceFactory>();
IInterface myInterface = factory.CreateInterface();
myInterface.SomeMethod1();
}
I am designing a System where the following scanario arise.
I have a method f1() for which behavior varies across implementation.
I have a method f2() for which behavior is same for all implementations.
I have designed as following:
interface I1
{
//Behaviour will vary across implementations
void f1();
//Same behaviour for all implementations
void f2();
}
abstract class C
{
//Implemented in the Base class
void f2()
{
}
}
public class C1:C,I1
{
//Implemented interface method
public f1()
{
}
}
public class C2:C,I1
{
//Implemented interface method
public f1()
{
}
}
Is the design is correct? Can anybody suggest any appropriate design in this sceanario ?
You should create just one abstract class with methods f1() and f2() as follows:
abstract class A
{
public abstract f1();
protected void f2()
{
}
}
class B : A
{
public override void f1()
{
}
}
Now whenever you create an class based upon A, they can specify their own behavior for method f1().
An alternative is to use a strategy pattern:
public interface IF1Strategy
{
void f1();
}
public sealed class C : I1
{
private readonly IF1Strategy _f1Strategy;
//strategy injected
public C(IF1Strategy strategy)
{
_f1Strategy = strategy;
}
void f2()
{
}
void f1()
{
//delegated to strategy
_f1Strategy.f1();
}
}
NB: Only suitable if your f1 strategy implementors do not need to call f2.
Advantages:
You can inject the appropriate strategy.
You can unit test strategies on their own.
Class C can change independant of the others i.e. that saves you maintaining a class heirachy. Note how I have sealed it.
In short, I am choosing Composition over inheritance
I am following OOPs design principle along with strategy pattern to provide a good solution for your problem.
these are the principle i follow:
1. Favor composition over inheritance.
2. Program to interface not implementation,
public interface I1VariedBehavior
{
void f1(); // Varies for the implementation.
}
public abstract class I1SameBehavior
{
public void f2()
{
Console.WriteLine("f2 same behavior");
}
}
public class F1Impl1 : I1VariedBehavior
{
public void f1() // f1 is own implementation
{
Console.WriteLine("F1 own implementation 1");
}
}
public class F1Impl2 : I1VariedBehavior
{
public void f1() // f1 is own implementation
{
Console.WriteLine("F1 own implementation 2");
}
}
public class C1 : I1SameBehavior
{
I1VariedBehavior strategy;
public C1(I1VariedBehavior strategy)
{
this.strategy = strategy;
}
public void f1()
{
strategy.f1();
}
}
public class Client
{
public static void Main(String[] args)
{
C1 c1 = new C1(new F1Impl1());
c1.f1();
c1.f2();
C1 c2 = new C1(new F1Impl2());
c2.f1();
c2.f2();
Console.Read();
}
}
output:
F1 own implementation 1
f2 same behavior
F1 own implementation 2
f2 same behavior
hope that helps.