Abstract Factory Pattern
Challenge You are working on an ORM (Object Relational Mapping) framework creation. The framework could be used in different databases like: . Sql Server . Oracle . MS Access . OleDb Based on the database type, you need to create related classes like: . SqlConnection, SqlCommand when Sql server . OracleConnection, OracleCommand when Oracle etc. How to create a family of related objects without implementation of them? Definition GoF Definition: "Provide an interface for creating families of related or dependent objects without specifying their concrete classes" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; namespace AbstractFactory { public interface IControlFactory { IPanel CreatePanel(); IButton CreateButton(); } public interface IPanel { Color BackColor { get ; set; } } public interface IButton { Color BackColor { get ; set; } } public class YellowButton : Button, IButton { public YellowButton() { BackColor = Color.Yellow; } public override Color BackColor { get; set; } } public class YellowPanel : Panel, IPanel { public YellowPanel() { BackColor = Color.Yellow; } public override Color BackColor { get; set; } } public class YellowControlFactory : IControlFactory { public IPanel CreatePanel() { return new YellowPanel(); } public IButton CreateButton() { return new YellowButton(); } } } **************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.Common; using System.Data.SqlClient; namespace AbstractFactory { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { SqlClientFactory factory = SqlClientFactory .Instance; DbConnection connection = factory.CreateConnection(); DbCommand command = factory.CreateCommand(); command.Connection = connection; command.CommandText = "query here"; command.ExecuteNonQuery(); } } } public abstract class DbProviderFactory { public abstract DbConnection CreateConnection(); public abstract DbCommand CreateCommand(); }
Comments