In my system I have 16 different classes alike used for statistics. They look like the following
public class myClass : myInheritage
{
private static myClass _instance;
public static myClass Instance
{
get { return _instance ?? (_instance = new myClass(); }
}
public static void Reset()
{
_instance = null;
}
}
They are all made into singletons
myInheritage looks like this:
public class myInheritage
{
int data = 0;
public myInheritage()
{
}
public int Data
{
get { return data; }
set { data+= value; }
}
}
The program is made, so the user chooses which class he wants to make statistics with.
Something like this is what I want
public void statistics(Object myObject, string name)
{
Object x = myObject;
x.Data = 10;
x.Data();
}
Called from another class
statistics(myClass.Instance, "myClass");
statistics(myClass2.Instance, "myClass2)";
So I want to dynamically change my instance in my statistics class.
Is that possible with .NET 2.0 ?
You could use reflection...
MethodInfo method = myObject.GetType().GetMethod("Reset");
if (method != null) method.Invoke(myObject, null);
If you can modify the classes themselves, a better approach might be to have each implement an interface (or base class) IResettable.
public interface IResettable
{
void Reset();
}
public class myClass : myInheritage, IResettable
{
public void Reset() { ... }
}
Then you could write the function against the interface:
public void statistics(IResettable myObject, string name)
{
myObject.Reset();
}
Yes. What you want here is a Strategy/Factory pattern. I name both as they could be used in conjunction for your case. There are great examples of these design patterns here and the following are detailed intros to the Strategy pattern and the Factory pattern. The former of the last two links also shows you how to combine the two to do exactly waht you require.
So in your case, you could set up the following interface
public interface IStatistics
{
// Some method used by all classes to impose statistics.
void ImposeStatistics();
}
Then in you singleton classes you could have
public class myClass : myInheritage, IStatistics
{
private static myClass _instance;
public static myClass Instance
{
get { return _instance ?? (_instance = new myClass()); }
}
public static void Reset()
{
_instance = null;
}
// You would also inherit from IStatistics in your other classes.
public void ImposeStatistics()
{
// Do stuff.
}
}
Then you would have a 'factory' class that imposes you stratgey at runtime.
public static class StatisticFactory
{
public static void ImposeStatistics(IStatistics statsType)
{
statsType.ImposeStatistics();
}
/// <summary>
/// Get the conversion type.
/// </summary>
/// <param name="col">The column to perform the conversion upon.</param>
public static IStatistics GetStatsType(string typeName)
{
switch (typeName)
{
case "BoseEinstein":
return new BoseEinsteinStats();
case "FermiDirac":
return new FermiDiracStats();
default:
return null;
}
}
}
You can then call this like
// Run stats.
IStatistics stats = StatisticFactory(GetStatsType("BoseEinstein"));
to get the statistics for the required class.
I hope this helps.
Related
What is the best approach to choosing between multiple interfaces based on the environment? My code is running in multiple environments. If its running on environment1 then the Singleton needs to implement IClass1.And on environment2 then it needs to implement IClass2. These two Interfaces share the same base adapter called IClassBase. My current approach only lets my singleton use the IClassBase's methods.
public interface IClassBase
{
public int BaseMethod();
}
public interface IClass1: IClassBase
{
void IClassMethod();
}
public interface IClass2: IClassBase
{
void IClass2Method();
}
public class Singleton: IClassBase
{
private static readonly Lazy<IClassBase> _instance
= new Lazy<IClassBase>(() => IsEnvironment1() ? new IClass1(): new IClass2());
public static IClassBase Instance { get { return _instance.Value; } }
public static bool IsEnvironment1()
{
// some logic to determine which environment
return true;
}
public int BaseMethod()
{
return 1;
}
}
I have a requirement of refactoring the code where I have multiple classes and the object of the classes need to be created dynamically depending upon the user request. Now the classes are all there and have no common methods within them that match each other. So I cannot add an interface to it and create a factory class that will return the interface reference referencing the actual class. Is there a way with generics or any other way to refactor this to be able to create objects dynamically. The approach we have now is that there is a main class where the object of each class is instantiated and all methods are being called. Can we implement a factory pattern without an interface or any solution to my scenario ? Please.
Adding sample code to explain the scenario.
public interface ITest
{
string TestMethod1(string st, int ab);
int TestMethod2(string st);
void TestMethod4(int ab);
float ITest.TestMethod3(string st);
}
public class Class1 : ITest
{
public string TestMethod1(string st, int ab)
{
return string.Empty;
}
public void TestMethod4(int ab)
{
throw new NotImplementedException();
}
public int TestMethod2(string st)
{
throw new NotImplementedException();
}
public float TestMethod3(string st)
{
throw new NotImplementedException();
}
}
public class Class2 : ITest
{
float ITest.TestMethod3(string st)
{
return float.Parse("12.4");
}
void ITest.TestMethod4(int ab)
{
throw new NotImplementedException();
}
public string TestMethod1(string st, int ab)
{
throw new NotImplementedException();
}
public int TestMethod2(string st)
{
throw new NotImplementedException();
}
}
public class Main
{
ITest test = null;
public ITest CreateFactory(TestType testType)
{
switch(testType)
{
case TestType.Class1:
test = new Class1();
break;
case TestType.Class2:
test = new Class2();
break;
}
return test;
}
}
enum TestType
{
Class1,
Class2
}
So, as in above, I can't have the interface because no common methods are in it. So what other solutions I can have, if I have an empty interface or abstract method, how will that help. Even if I put one common method in the interface and all classes implement it, since I am passing the reference to the interface, I can only access the common method from the interface reference.
My idea is to use something like the below, but not sure what the return type would or should be defined as.
public T CreateFactory(TestType testType)
{
switch(testType)
{
case TestType.Class1:
return GetInstance<Class1>("Class1");
case TestType.Class2:
return GetInstance<Class1>("Class2");
}
return null;
}
public T GetInstance<T>(string type)
{
return (T)Activator.CreateInstance(Type.GetType(type));
}
How do I define T here in the return is my concern and how can I invoke it, if anybody can help with that, then I think I am close to the solution.
Answer to my problem
public static T CreateFactory<T>()
where T: IFactory, new()
{
return new T();
}
I'm not saying totally understand the problem, but give it a shot...
Factory like class that you have:
class Factory
{
public static Visitable Create(string userInput)
{
switch (userInput)
{
case nameof(ClassA):
return new ClassA();
case nameof(ClassB):
return new ClassB();
default:
return null;
}
}
}
Types that you have to create:
class ClassA : Visitable
{
public void M1(){}
public override void Accept(Visitor visitor){visitor.Visit(this)}
}
class ClassB : Visitable
{
public void M2(){}
public override void Accept(Visitor visitor){visitor.Visit(this)}
}
Usage of the code:
var visitor = new Visitor();
var obj = Factory.Create("ClassA");
obj.Accept(visitor);
And the missing parts:
class Visitor
{
public void Visit(ClassA obj){ obj.M1(); } // Here you have to know what method will be called!
public void Visit(ClassB obj){ obj.M2(); } // Here you have to know what method will be called!
}
abstract class Visitable
{
public abstract void Accept(Visitor visitor);
}
This is called the Visitor pattern. If you know what methods need to be called Visitor.Visit than that is what you want.
I don't entirely understand your question but a basic assertion is wrong. I am concerned with your design given the basis of your question.
Regardless, my proposed solution:
You are saying that you don't have a common object (indirect, directly you stated: "I can't have the interface because no common methods are in it."
object is the common element.
I don't condone this but you could create a factory object that just returned object as the data type. The problem with this is you then have to cast it after the object creation which you may not mind...
internal class MyFactory
{
internal object CreateItem1() { return ...; }
internal object CreateItem2() { return ...; }
internal object CreateItem2(ExampleEnum e)
{
switch(e)
{
case e.Something:
return new blah();
default:
return new List<string>();
}
}
}
I have an object that only initializes itself with barebones data when constructed (fast), and loads itself for real (slow) when first accessed. The idea is that I'm creating a lot of these barebones objects at startup and hash them into a map, then fully load each object whenever it is individually accessed for the first time. The problem is that I cannot guarantee how clients will interact with this object, there are multiple public methods that might be invoked.
Is there a good pattern to support this kind of situation? The obvious (and my current) solution is to track state with an internal bool, check against that bool in every function that might be invoked, and load that way. But that requires code duplication of that behavior across all public functions, and is vulnerable to errors.
I can imagine a single point-of-entry method that then dishes out behaviors based on a client request type etc., but before I go consider going down that road I want to see if there's a commonly accepted approach/pattern that I might not be aware of. I'm doing this in C#, but any insight is appreciated.
If I understood what you want to achieve, you are looking for the Proxy Design Pattern, more specifically, a virtual Proxy.
Refer to http://www.dofactory.com/net/proxy-design-pattern
A small example would be something like:
public abstract class IObjectProvider
{
public abstract IObjectProvider Object{get;}
public abstract void doStuff();
}
public class RealObject : IObjectProvider
{
public RealObject()
{
//Do very complicated and time taking stuff;
}
public override IObjectProvider Object
{
get { return this; }
}
public override void doStuff()
{
//do this stuff that these objects normally do
}
}
public class ObjectProxy : IObjectProvider
{
private IObjectProvider objectInstance = null;
public override IObjectProvider Object
{
get
{
if (objectInstance == null)
objectInstance = new RealObject();
return objectInstance;
}
}
public override void doStuff()
{
if(objectInstance!=null)
objectInstance.doStuff();
}
}
public class SkeletonClass
{
public IObjectProvider Proxy1 = new ObjectProxy();
public IObjectProvider Proxy2 = new ObjectProxy();
}
static void Main(String[] args)
{
//Objects Not Loaded
SkeletonClass skeleton = new SkeletonClass();
//Proxy1 loads object1 on demand
skeleton.Proxy1.Object.doStuff();
//Proxy2 not loaded object2 until someone needs it
}
Here's an example of dynamic proxy approach.
using System;
using System.Diagnostics;
using Castle.DynamicProxy; //Remember to include a reference, too. It's nugettable package is Castle.Core
namespace ConsoleApp
{
public class ActualClass
{
//Have static instances of two below for performance
private static ProxyGenerator pg = new ProxyGenerator();
private static ActualClassInterceptor interceptor = new ActualClassInterceptor();
//This is how we get ActualClass items that are wrapped in the Dynamic Proxy
public static ActualClass getActualClassInstance()
{
ActualClass instance = new ActualClass();
return pg.CreateClassProxyWithTarget<ActualClass>(instance, interceptor);
}
//Tracking whether init has been called
private bool initialized = false;
//Will be used as evidence of true initialization, i.e. no longer null
private int? someValue = null;
public void Initialize()
{
if (!initialized)
{
//do some initialization here.
someValue = -1; //Will only get set to non-null if we've run this line.
initialized = true;
}
}
//Any methods you want to intercept need to be virtual!
public virtual int replaceValue(int value)
{
//below will blow up, if someValue has not been set to -1 via Initialize();
int oldValue = someValue.Value;
someValue = value;
return oldValue;
}
//block off constructor from public to enforce use of getActualClassInstance
protected ActualClass() { }
}
public class ActualClassInterceptor : ActualClass, IInterceptor
{
public void Intercept(IInvocation invocation)
{
//Call initialize before proceeding to call the intercepted method
//Worth noting that this is the only place we actually call Initialize()
((ActualClass)invocation.InvocationTarget).Initialize();
invocation.Proceed();
}
}
class Program
{
static void Main(string[] args)
{
ActualClass instance1 = ActualClass.getActualClassInstance();
ActualClass instance2 = ActualClass.getActualClassInstance();
int x1 = instance1.replaceValue(41);
int x2 = instance2.replaceValue(42);
int y1 = instance1.replaceValue(82);
Debug.Assert(y1 == 41);
int y2 = instance2.replaceValue(84);
Debug.Assert(y2 == 42);
var read = Console.ReadKey();
}
}
}
I realized that I should have only one instance of an object called StdSchedulerFactory running at a time. So far I instantiated the object like this
StdSchedulerFactory sf = new StdSchedulerFactory(properties);
And properties is a NameValueCollection.
How can I write a Singleton class for this object so that the variable sf will always have one instance throughout the program?
Part of the Singleton pattern is typically a private constructor, so that other classes can not make new instances.
The workaround for parameters coming from outside the class is to add a "Init" or "Configure" function:
public static void Configure(NameValueCollection properties)
{
}
Of course, if you forget to call this function, you may get behavior you don't want; so you may want to set a "Configured" flag or something like that so your other functions can react appropriately if this function has not yet been called.
Here is a basic Singleton implementation. It is not thread-safe.
public sealed class StdSchedulerFactory
{
private static readonly StdSchedulerFactory instance;
private NameValueCollection _properties;
private StdSchedulerFactory(NameValueCollection properties)
{
_properties = properties;
}
public static StdSchedulerFactory GetInstance(NameValueCollection properties)
{
if (instance == null)
{
instance = new StdSchedulerFactory(properties);
}
else
{
return instance;
}
}
}
this is my two favorite way implementing simple singleton pattern. The second one is just easier when debugging :)
public sealed class SingletonOne
{
private static readonly Lazy<SingletonOne> instance = new Lazy<SingletonOne>(() => new SingletonOne());
private Lazy<Controller> controller = new Lazy<Controller>(() => new Controller(properties));
private static object properties = null;
public static SingletonOne Instance { get { return instance.Value; } }
public Controller GetController(object properties)
{
SingletonOne.properties = properties;
return this.controller.Value;
}
}
public sealed class SingletonTwo
{
private static readonly SingletonTwo instance = new SingletonTwo();
private Controller controller;
private static object properties = null;
public static SingletonTwo Instance
{
get
{
return SingletonTwo.instance;
}
}
public Controller GetController(object properties)
{
SingletonTwo.properties = properties;
if(this.controller == null)
{
this.controller = new Controller(SingletonTwo.properties);
}
return this.controller;
}
}
public class Controller
{
public Controller(object properties) { }
}
I have a static Class and within it I have multiple public static attributes. I treat this class as my global class.
However now I need to treat this class as a variable so that I can pass it to a method of another class for processing..
I can't instantiate this class.. So in effect I can only assign the variables inside this class.
Is my understanding correct or am I missing something?
public static class Global
{
public const int RobotMax = 2;
// GUI sync context
public static MainForm mainForm;
public static SynchronizationContext UIContext;
// Database
public static Database DB = null;
public static string localDBName = "local.db";
public static Database localDB = null;
public static Database ChangeLogDB = null;
public static string changeLogDBName = "ChangeLog.db";
}
Let say I have a class like this, and I need to somehow keep a copy of this in another class maybe
public static class Global_bk
{
public const int RobotMax = 2;
// GUI sync context
public static MainForm mainForm;
public static SynchronizationContext UIContext;
// Database
public static Database DB = null;
public static string localDBName = "local.db";
public static Database localDB = null;
public static Database ChangeLogDB = null;
public static string changeLogDBName = "ChangeLog.db";
}
I need to copy the contents from Global to Global_bk.
And after that I need to compare the contents of the two classes in a method like
static class extentions
{
public static List<Variance> DetailedCompare<T>(T val1, T val2)
{
List<Variance> variances = new List<Variance>();
FieldInfo[] fi = val1.GetType().GetFields();
foreach (FieldInfo f in fi)
{
Variance v = new Variance();
v.Prop = f.Name;
v.valA = f.GetValue(val1);
v.valB = f.GetValue(val2);
if (!v.valA.Equals(v.valB))
variances.Add(v);
}
return variances;
}
}
class Variance
{
string _prop;
public string Prop
{
get { return _prop; }
set { _prop = value; }
}
object _valA;
public object valA
{
get { return _valA; }
set { _valA = value; }
}
object _valB;
public object valB
{
get { return _valB; }
set { _valB = value; }
}
}
So on my main form, how do I go about calling the compare method and passing the static Global class inside?
example: extentions.DetailedCompare(Global, Global_bk) ? Of course this would give me an error because I cant pass a type as a variable.
Please help me, this is driving me nuts...
How about the singleton pattern ? You can pass reference to shared interface (IDoable in exable below) and still have just one instance.
I.E.:
public interface IDoable {
int Value { get; set; }
void Foo();
}
public static class DoableWrapper {
private MyDoable : IDoable {
public int Value { get;set; }
public void Foo() {
}
}
private static IDoable s_Doable = new MyDoable();
public static IDoable Instance {
get { return s_Doable; }
}
}
Singleton is the way to go here. You can do it like this:
internal class SomeClass
{
private static SomeClass singleton;
private SomeClass(){} //yes: private constructor
public static SomeClass GetInstance()
{
return singleton ?? new SomeClass();
}
public int SomeProperty {get;set;}
public void SomeMethod()
{
//do something
}
}
The GetInstance Method will return you a SomeClass object that you can edit and pass into whatever you need.
You can access the members with classname.membername.
internal static class SomeClass
{
public static int SomeProperty {get;set;}
public static void SomeMethod()
{
//do something
}
}
static void main()
{
SomeClass.SomeProperty = 15;
SomeClass.SomeMethod();
}
The only way you are going to obtain a variable with the "class" information is using reflection. You can get a Type object for the class.
namespace Foo {
public class Bar
{
}
}
Type type = Type.GetType("Foo.Bar");
Otherwise, if you are really describing a class "instance" then use an object and simply instantiate one.
C# offers no other notation for class variables.