Invoking a singleton class in a abstract factory method - c#

I have a class with abstract factory method as follows:
public abstract class OpClass
{
public abstract IHou OperationInvoke(string opClass);
}
public class FactoryClass : OpClass
{
public override IHou OperationInvoke(string opClass)
{
if(opClass == "T")
{
//new Treasure();
}
}
}
and the concrete "Treasure" class goes like this:
public interface IHou
{
void Operation(Player p, List<Player> lstPlayers);
}
public sealed class Treasure : IHou
{
private static Treasure instance = null;
private static readonly object padlock = new object();
Treasure()
{
}
public static Treasure Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Treasure();
}
return instance;
}
}
}
public void Operation(Player p, List<Player> lstPlayers)
{
p.Points = p.Points + 200;
}
}
In my main Method I am trying to call it as:
Main()
{
Player p = //Populate from db;
List<Player> players = //populate from db
OpClass c = new FactoryClass();
IHou output = c.OperationInvoke("T");
output.Operation(p, players);
}
But the thing I need a single instance of "Treasure" class so I had the idea of changing the normal "Treasure" class to a singleton class.
So in this scenario how do I create a single instance of Treasure class and also preserve facory pattern? And if it's not possible to implement whats the best solution if the number of concrete classes get added like Treasure , House , Blocks etc.?
Edit : Is it not appropriate to use factory pattern here , as my understanding was if we have many classes with common behaviours like in this Treasure , and say one more class "House" gets added which calculates points in a different way , I will allow the factory to decide to invoke which one to instantiate.

you can make use of Flyweight pattern for this, in this pattern you will store instance in cache or dictionary and return it from the factory
with the help of generics based implementation of factory as below you dont need to add more cases , it will create class based on Template type T. you can visit article link below have same king of implemenration.
public class FlyWeidhtFactory
{
Dictionary<string,IHou> dic = new Dictionary<string,IHou>();
public IHou OperationInvoke<T>(string opClass) where T: IHou
{
Type type = typeof(T);
string fullname = type.FullName;
if(!dic.Contains(fullname)
{
Object obj = Activator.CreateInstance(type);
dic[fullname] = (T)obj;
//no need of more cases
}
return dic[opClass];
}
}
pattern ensure that you are going to create many objects, and by above implementation you are sure that only one instance of you class will get created. no need to go for singleton pattern.
Make your concrete class internal sealed, so it will not be visible outside you assembly.
Above is just suggestion based on your question.
Articles for factory and flyweight :
Flyweight Design Pattern
Factory Design Pattern With Generics

Just return the singleton instance in the factory.
Your factory has the responsibility of knowing how to 'make'. In the case of Treasure, there is only one instance, so the Factory just returns that.
The fact that you are returning shared or unshared instances based on a key makes your code similar to flyweight. If no other code needs to create Treasure outside the factory, then you do not need a Singleton. You can force the classes to be instantiated via the factory by making them nested classes of the factory.
So make Treasure a nested class of the factory with a private constructor. Or make it a private nested class and use the factory method to return an abstract base.

Related

Using the Singleton pattern with an interface in C#

Note: Even though there are a lot of similar questions, non that i have found answered my question.
Problem:
I would like to implement a class in C# which uses the singleton pattern in the following way.
namespace DAL
{
public class CDAL : IDAL
{
/* Singleton Pattern */
private CDAL instance = null;
private CDAL()
{
}
public IDAL getInstance()
{
if (instance != null)
{
return instance;
}
else
{
CDAL.instance = new CDAL();
return CDAL.instance;
}
}
}
}
the problem is that instance and the method getInstance should be static, as i want to 'ask' the class for that instance and not an object.
but using c# i can't seem to do anything static in an interface.
how can i solve this?
You're right, you cannot do anything static on an interface, since it does not make any sense.
Use an abstract class instead of the interface to implement static logic.
It does not make any sense creating an interface with a static member.
Interfaces are a contract while the static member is always accessed by the class name, not the instance name. so briefly your interface does not know which the correct instance implementing the right logic.
in your case you don't need your method getInstance() to be defined in the interface.
Interface when used with Singleton is often just for unit testing purposes

How do I write an interface or abstract class that specifies creation logic?

I have a generic class that deals with widgets that can be deserialized from strings. Instances of the generic class will take the type of one of these widgets as a template parameter, and then create these widgets from strings. I wish to use the covariance properties of C#'s generics to write code like WidgetUser<IWidget> to deal with objects that may be WidgetUser<RedWidget> or WidgetUser<BlueWidget>. The problem is that to create a widget from a string inside of WidgetUser<T>, I'm forced to add new() as a guard. This makes WidgetUser<IWidget> an invalid type. Currently, I have code like this:
interface IWidget
{
// Makes this widget into a copy of the serializedWidget
void Deserialize(string serializedWidget);
}
class WidgetUser<T> where T : IWidget, new()
{
public void MakeAndUse(string serializedWidget)
{
var widget = new T();
widget.Deserialize(serializedWidget);
Use(widget);
}
}
With this code, I can make WidgetUser<BlueWidget> just fine, because BigWidget satisfies new(). I cannot write WidgetUser<IWidget> because instances of IWidget (or an equivalent abstract class) are not guaranteed to work with new(). A workaround could be this:
abstract class WidgetUser
{
public abstract void MakeAndUse();
}
class WidgetUser<T> : WidgetUser
where T : IWidget, new()
{
/* same as before but with an 'override' on MakeAndUse */
}
With this code, I can create a WidgetUser<BlueWidget> then write code that deals with just WidgetUser. I could have similar code with an abstract class BaseWidget instead of IWidget that accomplishes almost the same thing. This is functional, but I suspect there is a more direct approach that doesn't force me to define a dummy class. How can I convey my intent to the type system without creating dummy classes or extra factories. I just want an interface that says "you can make one of these from a string".
TL;DR:
Is there some way to write an interface or abstract class that lets me create an instance from a string but doesn't require me to have new() as a guard on WidgetUser<T>?
The problem here is that your Deserialize() method should be a static method. Therefore it should not be a member of IWidget itself - it should be a member of a factory interface, or it should be a static member of a concrete Widget class which is called from a concrete factory method. I show the latter approach below.
(Alternatively, you could use a Func<IWidget> delegate to specify it, but it's more usual to provide a full factory interface.)
So I suggest you create the factory interface:
interface IWidgetFactory
{
IWidget Create(string serialisedWidget);
}
Then remove the Deserialize() from IWidget:
interface IWidget
{
// .. Whatever
}
Then add a static Deserialize() method to each concrete implementation of IWidget:
class MyWidget: IWidget
{
public static MyWidget Deserialize(string serializedWidget)
{
// .. Whatever you need to deserialise into myDeserializedObject
return myDeserializedObject;
}
// ... Any needed IWidget-implementing methods and properties.
}
Then implement the factory for your concrete widget class using the static Deserialize() method from the concrete widget class:
sealed class MyWidgetFactory : IWidgetFactory
{
public IWidget Create(string serialisedWidget)
{
return MyWidget.Deserialize(serialisedWidget);
}
}
Then add a constructor to your WidgetUser class which accepts an IWidgetFactory and use it in MakeAndUse():
class WidgetUser
{
public WidgetUser(IWidgetFactory widgetFactory)
{
this.widgetFactory = widgetFactory;
}
public void MakeAndUse(string serializedWidget)
{
var widget = widgetFactory.Create(serializedWidget);
Use(widget);
}
private readonly IWidgetFactory widgetFactory;
}
Note that in this scenario, you no longer need the type argument for WidgetUser, so I have removed it.
Then when you create the WidgetUser you must supply a factory:
var widgetUser = new WidgetUser(new MyWidgetFactory());
...
widgetUser.MakeAndUse("MySerializedWidget1");
widgetUser.MakeAndUse("MySerializedWidget2");
Passing in a factory allows a lot more flexibility.
For example, imagine that your serialization scheme included a way of telling from the serialized string which kind of widget it is. For the purposes of simplicity, assume that it starts with "[MyWidget]" if it's a MyWidget and starts with ["MyOtherWidget"] if it's a MyOtherWidget.
Then you could implement a factory that works as a "virtual constructor" that can create any kind of Widget given a serialization string as follows:
sealed class GeneralWidgetFactory: IWidgetFactory
{
public IWidget Create(string serialisedWidget)
{
if (serialisedWidget.StartsWith("[MyWidget]"))
return myWidgetFactory.Create(serialisedWidget);
else if (serialisedWidget.StartsWith("[MyOtherWidget]"))
return myOtherWidgetFactory.Create(serialisedWidget);
else
throw new InvalidOperationException("Don't know how to deserialize a widget from: " + serialisedWidget);
}
readonly MyWidgetFactory myWidgetFactory = new MyWidgetFactory();
readonly MyOtherWidgetFactory myOtherWidgetFactory = new MyOtherWidgetFactory();
}
Note that this is generally not the best way to do things - you are better using a Dependency Container such as Autofac to manage this kind of thing.
I would implement WidgetFactory and call WidgetFactory.Create<T>(serializedWidget) to avoid the usage of new T()

How to keep a class from being instantiated outside of a Factory

I have a Factory. I do not want to allow classes that this factory produces to be instantiated outside of the factory. If I make them abstract, static, or give them private constructors then they won't be instantiable at all! Is this a language restriction or what?
I don't want to allow this
var awcrap = new Extrude2013 (); // BAD !!!
awcrap.extrudify (); // I don't want to allow this
Rest of code:
using System;
namespace testie
{
public enum ExtrudeType { Extrude2013, Extrude2014 }
public interface IExtrudeStuff {
void extrudify();
}
public class Extrude2013 : IExtrudeStuff {
public void extrudify(){
Console.WriteLine ("extrudify 2013");
}
}
public class Extrude2014 : IExtrudeStuff {
public void extrudify(){
Console.WriteLine ("extrudify 2014");
}
}
public static class ExtrudeFactory {
public static IExtrudeStuff Create(ExtrudeType t) {
switch (t) {
case ExtrudeType.Extrude2013: return new Extrude2013 ();
case ExtrudeType.Extrude2014: return new Extrude2014 ();
default: return null;
}
}
}
class MainClass {
public static void Main (string[] args) {
// Now for the pretty API part
var o = ExtrudeFactory.Create (ExtrudeType.Extrude2013);
o.extrudify ();
var p = ExtrudeFactory.Create (ExtrudeType.Extrude2014);
p.extrudify ();
var awcrap = new Extrude2013 (); // BAD !!!
awcrap.extrudify (); // I don't want to allow this
}
}
}
You can't completely disallow this. Whether or not it's a language "restriction" would be a matter of opinion, but there are things that you could consider:
Make the constructor internal. This will allow any type within the declaring assembly to call the constructor, but nothing outside the assembly. This would mean that any code you write in that assembly to be responsible for calling the factory, and it also means that you could not declare subtypes of the class in another assembly, since it would be unable to call the constructor.
A similar approach would be to make the class you expose abstract (or an interface), then declare an internal (or even private as a subclass of the factory, since it would never be referenced outside of the factory) type that implements the abstract class or interface.
Require a token that only the factory can provide in the constructor. This is how the DataTable class works. While the constructor could still be called, the user would have to pass in null for the value and it would at least be obvious that they shouldn't be doing this.
The whole point of Factory Pattern is that only the Factory knows how to choose and make an object and it only exposes the instantiated object's functionality through an interface not a concrete class. Making the object's constructor private fails because Factory itself cannot instantiate it.
Solution:
1- Define an interface class which all types of the Extrude20XX classes implement it such as IExtrudeStuff.
2- Wrap the Extrude20XX classes inside the class of Factory as private nested classes.
3- Implement the interface IExtrude in all the ExtrudeXX classes.
4- Write a (static) Create (t) method like:
public static class ExtrudeFactory {
public static IExtrudeStuff Create(ExtrudeType t) {
{
switch (t) {
case ExtrudeType.Extrude2013: return new Extrude2013 ();
case ExtrudeType.Extrude2014: return new Extrude2014 ();
default: return null;
}
}
}

Multiple implementations for one interface with DI

Right now I'm trying to teach myself the Dependency Injection pattern with the IOC-container from Autofac. I've come up with a very simple example, which is presented below. Although the example is simple, I fail to get it working properly.
Here are my classes/interfaces:
Two monsters, both implementing the IMonster interface:
interface IMonster
{
void IntroduceYourself();
}
class Vampire : IMonster
{
public delegate Vampire Factory(int age);
int mAge;
public Vampire(int age)
{
mAge = age;
}
public void IntroduceYourself()
{
Console.WriteLine("Hi, I'm a " + mAge + " years old vampire!");
}
}
class Zombie : IMonster
{
public delegate Zombie Factory(string name);
string mName;
public Zombie(string name)
{
mName = name;
}
public void IntroduceYourself()
{
Console.WriteLine("Hi, I'm " + mName + " the zombie!");
}
}
Then there's my graveyard:
interface ILocation
{
void PresentLocalCreeps();
}
class Graveyard : ILocation
{
Func<int, IMonster> mVampireFactory;
Func<string, IMonster> mZombieFactory;
public Graveyard(Func<int, IMonster> vampireFactory, Func<string, IMonster> zombieFactory)
{
mVampireFactory = vampireFactory;
mZombieFactory = zombieFactory;
}
public void PresentLocalCreeps()
{
var vampire = mVampireFactory.Invoke(300);
vampire.IntroduceYourself();
var zombie = mZombieFactory.Invoke("Rob");
zombie.IntroduceYourself();
}
}
And finally my main:
static void Main(string[] args)
{
// Setup Autofac
var builder = new ContainerBuilder();
builder.RegisterType<Graveyard>().As<ILocation>();
builder.RegisterType<Vampire>().As<IMonster>();
builder.RegisterType<Zombie>().As<IMonster>();
var container = builder.Build();
// It's midnight!
var location = container.Resolve<ILocation>();
location.PresentLocalCreeps();
// Waiting for dawn to break...
Console.ReadLine();
container.Dispose();
}
And this is my problem:
During runtime, Autofac throws an exception on this line:
var vampire = mVampireFactory.Invoke(300);
It seems that the mVampireFactory is actually trying to instantiate a zombie. Of course this won't work since the zombie's constructor won't take an int.
Is there a simple way to fix this?
Or did I get the way Autofac works completely wrong?
How would you solve this problem?
Your inversion of control container is not a factory per se. Your case is a perfect fit for the factory pattern.
Create a new abstract factory which is used to create your monsters:
public interface IMonsterFactory
{
Zombie CreateZombie(string name);
Vampire CreateVampire(int age);
}
And then register its implementation in Autofac.
Finally use the factory in your class:
class Graveyard : ILocation
{
IMonsterFactory _monsterFactory;
public Graveyard(IMonsterFactory factory)
{
_monsterFactory = factory;
}
public void PresentLocalCreeps()
{
var vampire = _monsterFactory.CreateVampire(300);
vampire.IntroduceYourself();
var zombie = _monsterFactory.CreateZombie("Rob");
zombie.IntroduceYourself();
}
}
You can of course use specific monster factories too if you want. None the less, using interfaces will imho make your code a lot more readable.
Update
But how would I implement the factory? On the one hand the factory should not use the IOC container to create the monsters, because that's considered evil (degrades the DI pattern to the service locator anti-pattern).
I'm getting so tired of hearing that SL is an anti-pattern. It's not. As with all patterns, if you use it incorrectly it will give you a disadvantage. That applies for ALL patterns. http://blog.gauffin.org/2012/09/service-locator-is-not-an-anti-pattern/
But in this case I don't see why you can't create the implementations directly in your factory? That's what the factory is for:
public class PreferZombiesMonsterFactory : IMonsterFactory
{
public Zombie CreateZombie(string name)
{
return new SuperAwesomeZombie(name);
}
public Vampire CreateVampire(int age)
{
return new BooringVampire(age);
}
}
It's not more complicated than that.
On the other hand the factory should not create the monsters itself, because that would bypass the IOC-container and tightly couple the factory and the monsters. Or am I on the wrong track again? ;-)
It doesn't matter that the factory is tighly coupled to the monster implementations. Because that's the purpose of the factory: To abstract away the object creation, so that nothing else in your code is aware of the concretes.
You could create SuperDeluxeMonsterFactory, MonstersForCheapNonPayingUsersFactory etc. All other code in your application wouldn't be aware of that you are using different monsters (by using different factories).
Each time you have to change concretes you either switch factory or you just modify the existing factory. No other code will be affected as long as your monster implementations do not violate Liskovs Substitution Principle.
Factory vs IoC container
So what's the difference between a factory and a IoC container then? The IoC is great at resolving dependencies for your classes and maintain the lifetimes (the container can for instance dispose all disposables automatically when a HTTP request ends)..
The factory on the other hand excels at creating objects for you. It does that and nothing else.
Summary
So if you somewhere in your code need to get a specific type of an implementation you typically should use a factory. The factory itself CAN use the IoC as a service locator internally (to resolve dependencies). That is OK since it's a implementation detail in the factory which do not affect anything else in your application.
Use the IoC container (through dependency injection) if you want to resolve a service (and do not care which implementation you get, or if you get a previously created instance).
Multiple implementations with Func<>
I am using the same logic as before, interface IMovement, three implementations, Cat, Dog, and Human.
I add an Enum, the MovementEnum. Because this approach uses DI to register a Func<> which returns and interface implementation depending on a specific key, you can use another type to represent the Enum.
public enum MovementEnum
{
Cat = 1,
Dog = 2,
Human = 3
}
public class Cat : IMovement
{
public string Walk()
{
return “Im a Cat, walking!”;
}
}
public class Dog : IMovement
{
public string Walk()
{
return “Im a Dog, walking!”;
}
}
public class Human : IMovement
{
public string Walk()
{
return “Im a human, walking!”;
}
}
To register first, you need to register the classes like this.
builder.Services.AddScoped<Dog>();
builder.Services.AddScoped<Human>();
builder.Services.AddScoped<Cat>();
And then register the Func<> with the Enum and the Interface. To choose between each class, I use a switch with the Enum.
builder.Services.AddTransient<Func<MovementEnum, IMovement>>(movementProvider => key =>
{
switch (key)
{
case MovimentEnum.Cat:
return movementProvider.GetService<Cat>();
case MovimentEnum.Dog:
return movementProvider.GetService<Dog>();
case MovimentEnum.Human:
return movementProvider.GetService<Human>();
default:
return null;
}
});
To use this in your controller, inject the Func<> like this.
[ApiController]
[Route("[controller]/[action]")]
public class MovementController : ControllerBase
{
private readonly IMovement _dogMovement;
private readonly IMovement _catMovement;
private readonly IMovement _humanMovement;
public MovementController(Func<MovementEnum, IMovement> serviceResolver)
{
_dogMovement = serviceResolver(MovementEnum.Dog);
_catMovement = serviceResolver(MovementEnum.Cat);
_humanMovement = serviceResolver(MovementEnum.Human);
}
[HttpGet]
public string GetCat()
{
return _catMovement.Walk();
}
[HttpGet]
public string GetDog()
{
return _dogMovement.Walk();
}
[HttpGet]
public string GetHuman()
{
return _humanMovement.Walk();
}
}

How to create a class without any constructor just like MessageBox class

How can i create a class with zero constructor, just like MessageBox class which has no constructor.
I can not make this class static, beacause a public static method is declared in it, and that method makes object of this class.
in C# 3.5
i want to make this class just like System.Windows.Forms.MessageBox class,
in which there is no constructor and
when we create object of this class error occurres :
this class has no constructor
where as a class with a private constructor when object creates error occurrs -
the constructor is not accessible due to its protection level.
The only way to create a class without a constructor is to use static class.
However, it seem you want to be able to create instances of this class from inside the class itself, which is not possible with a static class. For that, you should give the class a private constructor:
class Foo
{
private Foo() { }
public static Foo Create()
{
return new Foo(); // Only members of Foo can directly invoke the constructor.
}
}
If a method outside of Foo in the same assembly tries to instantiate Foo, the message given will be that the constructor is not accessible due to its protection level. If you try to access it from another assembly, it will give the message that Foo has no constructors.
The methods on MessageBox are static; you can do that with the static modifier:
public static class Foo {
public static void Bar() {...}
}
then:
Foo.Bar();
In earlier versions of c# (before static was allowed on classes) you had to cheat:
public class Foo {
private Foo() {} // hide the constructor
public static void Bar() {...}
}
Make it static class with no constructor or make it an Abstract class.
Make a static class, or make a class with a private constructor.
You can add public STATIC methods into your class and you would acheve the same as in messagebox.
Remember that static methods cannot access non static properties or methods in the same class.
Hope it helps.
Consider usage of Creational patterns, described in GOF ("Gang Of Four")
There are the following ways:
1) If you want to have only one instance of object to be created, use Singleton
There is a good example of thread-safe singleton on MSDN
In this strategy, the instance is created the first time any member of
the class is referenced
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
2) If you don't want to specify the exact class to create, use Factory method
Here is an extract from an article on C#-Corner Factory method Design pattern using C#
abstract class Factory
{
public abstract Product GetProduct(); //Factory Method Declaration
}
class concreteFactoryforProcuct1 : Factory
{
public override Product GetProduct() //Factory Method Implementation
{
return new Product1();
}
}
3) If there is a group of objects to be created this way, use Abstract factory
Here are extracts from an article on codeproject: Understanding and implementing abstract factory pattern in C#
Creating the Abstract Factory
interface IPhoneFactory //'I' stands for interface no relation with Iphone
{
ISmart GetSmart();
IDumb GetDumb();
}
Creating the Concrete Factories
class SamsungFactory : IPhoneFactory
{
public ISmart GetSmart()
{
return new GalaxyS2();
}
public IDumb GetDumb()
{
return new Primo();
}
}
...
Creating the Client
enum MANUFACTURERS
{
SAMSUNG,
HTC,
NOKIA
}
class PhoneTypeChecker
{
IPhoneFactory factory;
...
public PhoneTypeChecker(MANUFACTURERS m)
{
m_manufacturer= m;
}
public void CheckProducts()
{
switch (m_manufacturer)
{
case MANUFACTURERS.SAMSUNG:
factory = new SamsungFactory();
break;
case MANUFACTURERS.HTC:
factory = new HTCFactory();
break;
case MANUFACTURERS.NOKIA:
factory = new NokiaFactory();
break;
}
...
factory.GetSmart();
factory.GetDumb();
...
}
}
static void Main(string[] args)
{
PhoneTypeChecker checker = new PhoneTypeChecker(MANUFACTURERS.SAMSUNG);
checker.CheckProducts();
...
}
4) Use you common sense to develop your own design that would satisfy your needs.
If the purpose of it is not allowing user it instantiate new instances of the class you could make
all constructors less visible then public .
For example - protected.

Categories

Resources