Suppose we have an Abstract factory that creates for us some products. We know that the abstract factory can provide us some specific subclasses of the product but we don't want to check the type (this is the main reason for this pattern).
Now we need to create a specific view for each type of object, how can we do this without know the specific type?
Should the same factory create the different views?
Update: I created a github repo to try out all the different approaches.
For this problem we can look how abstract factory pattern implemented in ADO.NET.
We have an abstract factory called DbProviderFactory. There are several implementations of this factory like SqlClientFactory, MySqlClientFactory, OracleClientFactory etc.
For this problem, the products are database related objects like connection, command, data adapter etc.
At first our abstract factory gives us a connection (product). It could be MySqlConnection or OracleConnection. The only thing we know is, it is a DbConnection.
DbProviderFactory factory = ...
DbConnection conn = factory.CreateConnection();
Now we need to create a command object (view) that can be used along with this connection.
DbCommand cmd = conn.CreateCommand();
As you see, command (view) is created by the connection (product) not by the abstract factory.
But this is not quite true...
What actually happens is hidden in implementation details. When abstract factory creates the connection it passes itself to the connection. And when we ask for a command, the connection creates the command via the abstract factory provided.
So, if we return to your problem, implementation can be something like this.
interface IView {
IProduct Product { get; set; }
void Render();
}
interface IProduct {
IView CreateView();
}
interface IAbstractFactory {
IProduct CreateProduct();
IView CreateView();
}
class View1 : IView {
public IProduct Product { get; set; }
public void Render() {
Product1 p1 = (Product1)Product;
// Do product1 specific rendering here
}
}
class Product1 : IProduct {
private IAbstractFactory factory;
public Product1(IAbstractFactory factory) {
this.factory = factory;
}
public IView CreateView() {
IView view = factory.CreateView();
view.Product = this;
return this;
}
}
class Factory1 : IAbstractFactory {
IProduct CreateProduct() {
return new Product1(this);
}
IView CreateView() {
return new View1();
}
}
Related
Environment:
.Net, SQL Server, WinForms Desktop
Control Database (db1)
Customer Databases (db2, db3, db4, etc.)
Background:
Each of our customers requires their own database. It's a contractual obligation due to compliance with standards in certain industries. Certain users of our application only have access to specific databases.
Scenario:
The application user's username gets passed into our control database (db1) from the app on load. There's a lookup in there that determines what customer this user has access to and returns connection string info for connecting to the database of the determined customer (db2 or db3 or db4 or etc.) to be used for the life of the runtime. All of my business logic is in a DAL, as it should be, in a .Net class library.
Suggestions on the best way/ways to get the connection string information into the DAL WITHOUT passing into every constructor/method that is called on the DAL.
I came up with one possible solution, but want to pick your brains to see if there's another or better way.
Possible Solutions:
A Global module in the DAL that has public fields like "dbServer" and "dbName".
Set those and then use the DAL as needed. They would need to be set each time the DAL is used throughout the application, but at least I don't have to make the signature of every single constructor and method require connection string information.
A settings file (preferably XML) that the app writes to after getting the connection info and the DAL reads from for the life of the runtime.
Thoughts and/or suggestions? Thanks in advance.
A set up like this might help. If you are going the IoC way, then you can remove the parameterized constructor and make Connection object a dependency too. However, you will need to feed your dependency injection provider in code since connection string comes from database.
public class User
{
public string ConnectionString
{
get; set;
}
}
public class SomeBusinessEntity
{
}
public class CallerClass
{
public IBaseDataAccess<SomeBusinessEntity> DataAccess
{
get;
set;
}
public void DoSomethingWithDatabase(User user)// Or any other way to access current user
{
// Either have specific data access initialized
SpecificDataAccess<SomeBusinessEntity> specificDataAccess = new SpecificDataAccess<SomeBusinessEntity>(user.ConnectionString);
// continue
// have dependency injection here as well. Your IoC configuration must ensure that it does not kick in until we get user object
DataAccess.SomeMethod();
}
}
public interface IBaseDataAccess<T>
{
IDbConnection Connection
{
get;
}
void SomeMethod();
// Other common stuff
}
public abstract class BaseDataAccess<T> : IBaseDataAccess<T>
{
private string _connectionString;
public BaseDataAccess(string connectionString)
{
_connectionString = connectionString;
}
public virtual IDbConnection Connection
{
get
{
return new SqlConnection(_connectionString);
}
}
public abstract void SomeMethod();
// Other common stuff
}
public class SpecificDataAccess<T> : BaseDataAccess<T>
{
public SpecificDataAccess(string connectionString) : base(connectionString)
{
}
public override void SomeMethod()
{
throw new NotImplementedException();
}
public void SomeSpecificMethod()
{
using (Connection)
{
// Do something here
}
}
}
Create a ConnectionStringProvider class that will provide you the connection string
public class ConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider
// uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Using ConnectionStringProvider in your DAL
public class MyCustomerDAL
{
private ConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
_connectionStringProvider = new ConnectionStringProvider();
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
Setting/changing the connection string
new ConnectionStringProvider()
.SetCustomerConnectionString(connString);
Note
The reason i chose to use method instead of a get/set property in ConnectionStringProvider is because maybe in the future you decide to read/write these from a file, and while you could read/write from file in a property it's misleading to your consumer who thinks that a property will be a simple performance-less hit.
Using a function tells your consumer there might be some performance hit here, so use it wisely.
A little abstration for unit testing
Here is a slight variation that will enable you to abstract for unit testing (and eventually IoC)
public class MyCustomerDAL
{
private IConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
//since not using IoC, here you have to explicitly new it up
_connectionStringProvider = new ConnectionStringProvider();
}
//i know you don't want constructor, i included this to demonstrate how you'd override for writing tests
public MyCustomerDAL(IConnectionStringProvider connectionStringProvider)
{
_connectionStringProvider = connectionStringProvider;
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
// this interface lives either in a separate abstraction/contracts library
// or it could live inside of you DAL library
public interface IConnectionStringProvider
{
string GetCustomerConnectionString();
void SetCustomerConnectionString(string connectionString);
}
public class ConnectionStringProvider : IConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Appendix A - Using IoC and DI
Disclaimer: the goal of this next piece about IoC is not to say one way is right or wrong, it's merely to bring up the idea as another way to approach solving the problem.
For this particular situation Dependency Injection would make your solving the problem super simple; specifically if you were using an IoC container combined with constructor injection.
I don't mean it would make the code more simple, that would be more or less the same, it would make the mental side of "how do I easily get some service into every DAL class?" an easy answer; inject it.
I know you said you don't want to change the constructor. That's cool, you don't want to change it because it is a pain to change all the places of instantiation.
However, if everything were being created by IoC, you would not care about adding to constructors because you would never invoke them directly.
Then, you could add services like your new IConnectionStringProvider right to the constructor and be done with it.
Often i heard that "try to avoid if/switch constructions. If you have them then refactor them to subclasses"
I don't realize how this thing works.
Ok, you have a if/switch in your code. And you create several new classes. But to decide which class you will use you need to implement switch if in fabric class (where you generate these objects). Am i wrong?
P.S. Sorry for my English. I'm reader, not writer.
But to decide which class you will use you need to implement switch if
in fabric class (where you generate these objects). Am i wrong?
No, you are not wrong. While the Polymorphism over switches is a good thing, there are exceptions. One such exception is when you have parameterized factory, and that's absolutely acceptable. So instead of your client code creating specialized classes based on conditions, you will ask such factory to create them for you. Advantage is Factory will solely be responsible for creating those class instances, and if new class is introduced only factory will be modified not client code.
So instead of this:
public class Client {
public string Serialize<T>(string contentType, T instance) where T : class {
switch(contentType) {
case "XML":
return new XMLSerializer().Serialize(instance);
case "JSON":
return new JSONSerializer().Serialize(instance);
}
}
}
You will have this:
public interface ISerializer {
string Serialize(object instance);
object Deserialize(string content);
}
public class XMLSerializer : ISerializer { }
public class JSONSerializer : ISerializer { }
public class SerializerFactory() {
public static ISerializer CreateSerializer(string type) {
switch(type) {
case "XML":
return new XMLSerializer();
case "JSON":
return new JSONSerializer();
}
}
}
public class Client {
public string ParseAPIResponse(string contentType, string responseData) {
ISerializer serializer = SerializerFactory.CreateSerializer(contentType);
var responseObj = serializer.Deserialize(responseData);
}
}
Note there can be only one reason for Factory to change and that is introduction of new Serializer, so we are good on SRP here. Going even further there are ways by which you can avoid modifying factory too, using config files to store identifier-type mappings or simply exposing another method on factory to allow it's users to register new types etc. That's on you.
But I don't understand it, could someone explain this for me?
“Favour object [aggregation] over class inheritance” is an important design principal to handle change. how this principal is achieved in adapter pattern?
The class Adapter simply uses an instance of class A instead of inheriting from class A.
The adapter is basically a shell to class A knowing its methods and providing access by decorating A with a different set of methods matching the required contracts by actors using the adapter.
interface ListAdapter {
Object head()
ListAdapter tail();
}
class SimplestQueue implements ListAdapter {
private List<?> list;
public SimplestQueue(final List<?> list) { this.list = list.clone(); }
public Object head() { return this.list.get(0); }
public ListAdapter tail() { return new SimplestQueue (this.list.subList(1, this.list.size())); }
}
Usage:
final ListAdapter queue = new SimplestQueue(new ArrayList());
I am currently working on a project with NHibernate that requires security and auditing aspects. Those two seem to be perfect fits for the decorator pattern. Therefore my first step was to extract an interface for the entities to be decorated. Next, I decorated the relevant repositories to return decorated entities that implement the required auditing and security respectively. This works as expected.
However, a problem arises when NHibernate is asked to save a decorator instead of the base entity. Consider the following model as a simple example. It consists of an Engine that can be composed from multiple components.
public interface IEngine {
void AddComponent(IComponent component);
// Other Engine methods
}
public interface IComponent {
// Component methods
}
// Component basic entity mapped via NHibernate
public class Component : IComponent {
}
// Engine basic entity mapped via NHibernate
public class Engine {
private IList<IComponent> _components;
public Engine(IEnumerable<IComponent> components) {
_components = components.ToList();
}
public void AddComponent(IComponent component) {
_components.Add(component);
}
// Other engine methods
}
// Component security decorator
public class SecurityComponent : IComponent {
private readonly IComponent _innerComponent;
public SecurityComponent(IComponent innerComponent) {
_innerComponent = innerComponent;
}
// delegated and changed methods
}
// Engine security decorator
public class SecurityEngine {
private readonly IEngine _innerEngine;
public SecurityEngine(IEngine innerEngine) {
_innerEngine = innerEngine;
}
// delegated and changed methods
}
The code that is responsible for creating and saving Engines does not know anything about security decorators:
var components = componentRepository.RetrieveMatchingComponents(); // because the repository is decorated, this method returns SecurityComponents
var engine = new Engine(components);
engineRepository.Create(engine); // will fail because NHibernate cannot deal with the decorators referenced in the Engine
The only solution I can currently think of is to move the object creation into a factory that can also be decorated by the security code. The security factory would
need to decapsulate the SecurityComponents in order to construct a inner engine consisting only of basic entities. In addition the SecurityEngine would need to
decapsulate all incoming SecurityComponents. Finally the SecurityEngineRepository would need to decapsulate incoming SecurityEngines so that the innermost repository
that calls Session.Save receives only a basic entity Engine consisting only of basic entity Components. For example:
public class SecurityComponent : IComponent {
private readonly IComponent _innerComponent;
public SecurityComponent(IComponent innerComponent) {
_innerComponent = innerComponent;
}
public IComponent Decapsulate() { return _innerComponent; }
// delegated and changed methods
}
public class SecurityEngine {
private readonly IEngine _innerEngine;
public SecurityEngine(IEngine innerEngine) {
_innerEngine = innerEngine;
}
public void AddComponent(IComponent component) {
// do security stuff (e.g check if adding components is allowed)
IComponent result;
if (component is SecurityComponent) {
result = ((SecurityComponent)component).Decapsulate();
} else {
result = component;
}
_components.Add(result);
}
// other delegated and changed methods
}
public interface IEngineFactory {
IEngine CreateEngine(IEnumerable<IComponent> components);
}
public class EngineFactory : IEngineFactory {
public IEngine CreateEngine(IEnumerable<IComponent> components) { return new Engine(components); }
}
public class SecurityEngineFactory : IEngineFactory {
// decorator constructor
public IEngine CreateEngine(IEnumerable<IComponent> components) {
// decapsulate security components
var innerEngine = _innerEngineFactory.CreateEngine(decapsulatedComponents);
return new SecurityEngine(innerEngine);
}
}
The engine construction code:
var components = componentRepository.RetrieveMatchingComponents(); // because the repository is decorated, this method returns SecurityComponents
var engine = engineFactory.CreateEngine(components); // SecurityEngineFactory will return a SecurityEngine with a well formed inner Engine
engineRepository.Create(engine); // SecurityEngineRepository will decapsulate the SecurityEngine
This solution seems like a code smell to me. Is there a general pattern to solve this problem? Any suggestions on how to improve this solution?
i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.