Pattern for class instantiation from only one single place? - c#

C# .Net 4.0
I'd like to know how I can have a class which can only be instantiated from one single place. An example:
I've got a Provider class. This class exposes a method called GetData. When GetData is called, the Provider will instanciate a Data class, populate and return it. The Data class cannot be instanciated by anybody different then the Provider, so the only way to access the data will be through the Provider. Once GetData is called and a caller has received the Data class instance, he should be able to access properties/methods of this class.
How can this be done? Is there a pattern for this sort of problem? A short sample would be highly appreciated. Thanks in advance!

It sounds like you are looking for the factory pattern:
The factory pattern is a creational
design pattern used in software
development to encapsulate the
processes involved in the creation of
objects.
Basically your Provider class is the factory that controlls the creation of instances of the Data class.
One thing you could do control this would be to place these two types in their own assembly and make the constructor for Data be internal but the class itself public. This would mean that anyone who references the assembly would be forced to use the Provider class to create instances of Data (unless they used reflection, of course).

Another solution would be to create an interface IData, and declare the Provider.GetData method to return IData instead of Data. Then you can have your Data class nested inside Provider. This way your Data class cannot be instantiated even by classes in the same assembly. Here is an example:
public interface IData
{
// properties and methods
}
public class Provider
{
public IData GetData()
{
return new Data();
}
private class Data : IData
{
// your implementation
}
}

Here is an example of what Andrew described:
public class Data
{
internal Data()
{
// internal constructor cannot be called from outside the assembly
}
// properties, fields and methods
}
public class Provider
{
public Data GetData()
{
return new Data();
}
}

public class Provider
{
protected Provider()
{
}
public static Provider CreateNewProvider()
{
return new Provider();
}
}

Related

Factory pattern: Restrict object construction to factory

I have a class T and a factory TFactory that creates objects of type T.
I want to make sure that only the factory is allowed to create new T objects.
A halfhearted solution would be to require the factory as a parameter in T's constructor, for the only purpose that only somebody who at least brings a factory object can create T's:
class T
{
public T(TFactory Tf)
{
if (!(Tf is TFactory))
throw new InvalidOperationException("No factory provided");
}
}
But wherever a TFactory is at hand, one could construct T's.
Another approach would be to check via stack tracing, if the constructor call really came from within a TFactory, but this seems overkill to me.
A third apporach would be to put both T and TFactory in an assembly of their own, ad make T's constructor internal. But a new project and assembly just for this purpose?
Any better idea anybody?
(Although my code is C#, this is probably a more general question)
Here's something very similar to your third approach: declare the factory as a inner class of T, and make T's constructor private:
public class T {
public class Factory {
public T GetT() {
return new T(); // simple implementation just for an example here
}
}
private T() {}
}
Since Factory is inside T, it can access the private constructor, but outside code cannot. If you don't want to create a separate assembly, you could consider this approach.
Note that you could still put the factory class and T in two different files, with partial classes:
public partial class T {
private T() {}
// other stuff about T here...
}
// in another file
public partial class T {
public class Factory {
public T GetT() {
return new T();
}
// other stuff about Factory here...
}
}
public abstract class T { }
public class TFactory
{
public T CreateT() => new TImpl();
private class TImpl : T { }
}
The second approach is the worst one. That behavior is absolutely unobvious and unclear to a client. Stack tracing also slows down execution. The 1st and the 2nd make sense.
If you want to have total control of instance creation put it into the type. Use a factory method. Remember, one should be reasonable when putting constraint on instance creation. E.g. the instance should be initiated with a polymorphal (virtual) method. One can't call such a method from a constructor (a very bad practice), so the method should be called after construction. For not to put that responsibility on the client, hide the constructor from one and provide a factory method.
abstract class Base
{
protected abstract void Initialize();
}
class Derived : Base
{
protected Derived() { /* ... */}
protected override void Initialize() { /* ... */}
public Derived CreateDerived()
{
var derived = new Derived();
derived.Initialize();
return derived;
}
}

Different property value for contracts

I have two interfaces implemented by one main class. How can i refactor my code in a way that on implementing each contract, the methods of each contract has a different value for a parameter such as DatabaseName.
Example :
Class1 Implements Interface1,Interface2
Interface1.GetData() has DatabaseName set to Database 1
Interface2.GetData() has DatabaseName set to Database 2
I can configure those value in the methods GetData() but i want a cleaner way of doing it.
Any pattern recommendation be that DI ,Domain driven ,even basic inheritance example which accomplishes the above is what i am looking for.
It sounds like all you need is explicit interface implementation:
public class Class1 : Interface1, Interface2
{
// Note the lack of access modifier here. That's important!
Data Interface1.GetData()
{
// Implementation for Interface1
}
Data Interface2.GetData()
{
// Implementation for Interface2
}
}
Obviously the two methods can call a common method with a parameter to specify the database name or similar.
Refactoring is usually motivated by noticing a code smell and the very fact that you ended up in a situation where you have to implement 2 abstraction which expose similar functionality is the code smell.
Without having more understanding of the problem I might not be able to provide you a conclusive answer but with limited understanding this is what I would propose. Have 2 different concrete implementation each implementing one interface and have a factory which would be injected to client and make the client make the deliberate decision which one of these implementation is needed. In case these concrete classes share common functionality you can always abstract that into a common parent class.
public interface ISQLReader
{
string GetData();
}
public interface IOracleReader
{
string GetData();
}
public abstract class Reader
{
protected void CommonFunctionaility()
{
}
}
public class MSSQLReader : Reader, ISQLReader
{
public string GetData()
{
return "MSSQL";
}
}
public class OracleReader : Reader, IOracleReader
{
public string GetData()
{
return "Oracle";
}
}
public interface IReaderFactory
{
OracleReader CreateOracleReader();
MSSQLReader CreateMSSQLReader();
}
public class ReaderFactory : IReaderFactory
{
public MSSQLReader CreateMSSQLReader() => new MSSQLReader();
public OracleReader CreateOracleReader() => new OracleReader();
}
public class ReaderClient
{
private IReaderFactory _factory;
public ReaderClient(IReaderFactory factory)
{
this._factory = factory;
}
}
Explicit interface implementation is technique that should restrict usage of the functionality until the client has made and explicit cast there by making a deliberate decision.

Factory Pattern to build many derived classes

I have a factory object ChallengeManager to generate instances of a Challenge object for a game I'm building. There are many challenges. The constructors for each Challenge class derivation are different, however there is a common interface among them, defined in the base class.
When I call manager.CreateChallenge(), it returns an instance of Challenge, which is one of the derived types.
Ideally, I would like to keep the code for the object construction inside the derived class itself, so all the code related to that object is co-located. Example:
class Challenge {}
class ChallengeA : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeA();
}
}
class ChallengeB : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeB();
}
}
Now, my ChallengeManager.CreateChallenge() call only needs to decide the class to call MakeChallenge() on. The implementation of the construction is contained by the class itself.
Using this paradigm, every derived class must define a static MakeChallenge() method. However, since the method is a static one, I am not able to make use of an Interface here, requiring it.
It's not a big deal, since I can easily remember to add the correct method signature to each derived class. However, I am wondering if there is a more elegant design I should consider.
I really like the pattern you are describing and use it often. The way I like to do it is:
abstract class Challenge
{
private Challenge() {}
private class ChallengeA : Challenge
{
public ChallengeA() { ... }
}
private class ChallengeB : Challenge
{
public ChallengeB() { ... }
}
public static Challenge MakeA()
{
return new ChallengeA();
}
public static Challenge MakeB()
{
return new ChallengeB();
}
}
This pattern has many nice properties. No one can make a new Challenge because it is abstract. No one can make a derived class because Challenge's default ctor is private. No one can get at ChallengeA or ChallengeB because they are private. You define the interface to Challenge and that is the only interface that the client needs to understand.
When the client wants an A, they ask Challenge for one, and they get it. They don't need to worry about the fact that behind the scenes, A is implemented by ChallengeA. They just get a Challenge that they can use.
You're "decentralizing" the factory, such that each subclass is responsible for creating itself.
More commonly you would have a central factory that would know about the possible subtypes and how to construct them (often enough, simply by creating a new instance and returning that instance typed as a common interface or common base class). That approach avoids the issue you currently have. I also see no benefit to your current approach. You are currently gaining no encapsulation or code reuse over the more typical implementation of a factory.
For additional reference, have a look at
http://www.oodesign.com/factory-pattern.html
Not necessarily the answer you are looking for but...
You can use following implementation, if you can move away from static method per class.
using System;
public class Test
{
public static void Main()
{
var c1 = ChallengeManager.CreateChallenge();
var c2 = ChallengeManager.CreateChallenge();
//var c = ChallengeManager.CreateChallenge<Challenage>(); // This statement won't compile
}
}
public class ChallengeManager
{
public static Challenage CreateChallenge()
{
// identify which challenge to instantiate. e.g. Challenage1
var c = CreateChallenge<Challenage1>();
return c;
}
private static Challenage CreateChallenge<T>() where T: Challenage, new()
{
return new T();
}
}
public abstract class Challenage{}
public class Challenage1: Challenage{}
public class Challenage2: Challenage{}

C# Interface with static property or methods?

I need to define a static property or method in certain classes of my bussiness logic, to explicity determine which classes are cacheables in Session or Cache of ASP.NET service. I'm thinking, static property or method in the interface would be perfect, but C# 4.0 doesn't support this.
All a need is be able to evaluate in a generic manager which classes are cacheables and, if they are, at what level: session (user) or cache (application).
Now I'm trying with a empty interface with T parameter to evaluate, but, maybe exists a better approach?? Thanks.
public interface ICacheable<T>
{
}
public class Country : ICacheable<CacheApplication>
{
}
public class Department : ICacheable<CacheUser>
{
}
public class Gestor<T>
{
// ...
if (typeof(T) is ICacheable<CacheApplication>)
{
}
// ...
}
How about using a custom attribute? Your classes then would look something like this:
[Cacheable(Level = CacheLevels.Application)]
public class Country { }
[Cacheable(Level = CacheLevels.User)]
public class Department { }
You can read here on how to create your own custom attribute and then access its value by using reflection.
You cant define static interfaces, for one thing, you cant make instances of static classes so you cant substitute them for others with the same base class.
You might be better off having a singleton instance of one class and using interfaces as normal. You could enforce one and one-only instance through a factory pattern too.

How would dependency injection apply to this scenario?

I'm using Ninject for constructor injection to create my concrete objects on the fly. However, I have a scenario where the class contains a method that accepts a string. Based on the value of the string, I would like to obtain a specific class. I accomplished this by creating a factory class to return the concrete class but wasn't sure if this was the best way. Any suggestions?
//Service class
public int GetEmployeeVacationDays(string employeeType)
{
IEmployee employee = EmployeeFactory.CreateEmployee(employeeType);
return employee.VacationDays();
}
//Factory class
public static IEmployee CreateEmployee(string employeeType)
{
if(employeeType == "Salary")
{
return new SalariedEmployee();
}
else
{
return new HourlyEmployee();
}
}
Dependency injection doesn't apply to your scenario. That's the factory pattern. You could configure Ninject to use the factory pattern to provide dependencies if you will for certain objects.
In fact you could entire replace the factory pattern with named bindings:
Bind<IEmployee>().To<FooEmployee>().Named("foo");
Bind<IEmployee>().To<BarEmployee>().Named("bar");
Bind<IEmployee>().To<BazEmployee>().Named("baz");
assuming that employeeType is a valid class name:
return System.Activator.CreateInstance(Type.GetType(className))

Categories