Abstract Factory Design Pattern (Sample in C# and VB .NET)

-->

Environment: Win2K, NT

Creational Pattern Abstract Factory
Reference:E. Gamma et al., "Design Patterns: Elements of Reusable Object-Oriented Software" ISBN 0-201-63361-2, Addison Wesley, 1995.

Context
An abstract factory provides an interface for creating families of related objects without specifying their concrete classes. Sometimes one wants to construct an instance of one of a suite of classes, deciding between the classes at the time of instantiation. In order to avoid duplicating the decision making everywhere an instance is created, we need a mechanism for creating instances of related classes without necessarily knowing which will be instantiated.

Solution
Create an Abstract Factory class to answer instances of concrete classes (usually subclasses). The class of the resultant instance is unknown to the client of the Abstract Factory.
There are two types of Abstract Factory: A Simple Abstract Factory is an abstract class defining Factory methods to answer instances of concrete subclasses. The choice of which subclass to instantiate is completely defined by which method is used, and is unknown to the client.
B The second form of Abstract Factory is an abstract class defining a common protocol of Factory methods. Concrete subclasses of the abstract factory implement this protocol to answer instances of the appropriate suite of classes. See below for an example, both VB .NET and C# implementation

Applicability
A Need to abstract from details of implementation of products -The system shall be independent of how its constituent pieces are created, composed, and represented. B Need to have multiple families of products - The system shall be configured with one of multiple families of products. C Need to enforce families of products that must be used together - A family of related product objects is designed to be used together, and you need to enforce this constraint. D Need to hide product implementations and just present interfaces - You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Characteristics
A An abstract factory is an object maker. B It typically can produce more than one type of object. C Each object that it produces is known to the receiver of the created object only by that object's interface, not by the object's actual concrete implementation. D The different types of objects that the abstract factory can produce are related -- they are from a common family E An abstract factory isolates concrete classes F It makes exchanging product families easy G It promotes consistency among products H It supports adding new kinds of products and their families.

Example
The Example here has an implementation of an Abstract Factory as an Interface IAVDevice that has methods that can create an Audio object and a Video object. The client Codes against IAVDevice and gets IAudio and IVideo interfaces. Passing "cd" in the command line creates a family of cd objects (Audio and Video) and "dvd" creates a family of dvd objects (Audio and Video). The client doesn't care which object (cd audio video or dvd audio video), IAVDevice interface returns as it codes against IAudio and IVideo interface.

using System;

public interface IAVDevice
{	
	IAudio GetAudio();
	IVideo GetVideo();
}		

public interface IVideo
{	
	string GetPictureQuality();
}

public interface IAudio
{	
	string GetSoundQuality();
}

class CCd:IAVDevice
{
	public IAudio GetAudio()
	{
		return new CCdAudio();
	}
	public IVideo GetVideo()
	{
		return new CCdVideo();
	}	
}

class CDvd:IAVDevice
{
	public IAudio GetAudio()
	{
		 return new CDvdAudio();
	}
	public IVideo GetVideo()
	{
		return new CDvdVideo();
	}	
}

class CCdAudio:IAudio 
{	
	public string GetSoundQuality()
	{
		return "CD Audio is better then DVD Audio";
	}
}

class CCdVideo:IVideo
{
	public string GetPictureQuality()
	{
		return "CD video quality is not as good as DVD";
	}
}

class CDvdAudio:IAudio 
{
	public string GetSoundQuality()
	{
		 return  "DVD Audio is not as good as CD Audio";
	}	
}

class CDvdVideo:IVideo
{	
	public string GetPictureQuality()
	{
		return "DVD video quality is better then CD";
	}
}

class CAVMaker
{	
	public IAVDevice AVMake(string xWhat)
	{
		switch (xWhat.ToLower())
		{
			case "cd":
				return new CCd();
			case "dvd":
				 return new CDvd();
			default:
				return new CCd(); 			
		}
	}
}

public class AbstractFactory
{
	static void Main(string[] args) 
	{
		CAVMaker objFactMaker = new CAVMaker();
		IAVDevice objFact;
		IAudio objAudio;
		IVideo objVideo;
		string strWhat;
		strWhat = args[0];
		objFact = objFactMaker.AVMake(strWhat);
		objAudio = objFact.GetAudio();
		objVideo = objFact.GetVideo();
		Console.WriteLine(objAudio.GetSoundQuality());
		Console.WriteLine(objVideo.GetPictureQuality());
	}
}

Imports System

Public Interface IAVDevice
    Function GetAudio() As IAudio
    Function GetVideo() As IVideo
End Interface

Public Interface IAudio
    Function GetSoundQuality() As String
End Interface

Public Interface IVideo
    Function GetPictureQuality() As String
End Interface

Class CCd
  Implements IAVDevice

  Public Function GetAudio() As IAudio Implements IAVDevice.GetAudio
      GetAudio = New CCdAudio()
  End Function

  Public Function GetVideo() As IVideo Implements IAVDevice.getVideo
      GetVideo = New CCdVideo()
  End Function
End Class

Class CDvd
  Implements IAVDevice

  Public Function GetAudio() As IAudio Implements IAVDevice.GetAudio
      GetAudio = New CDvdAudio()
  End Function

  Public Function GetVideo() As IVideo Implements IAVDevice.GetVideo
      GetVideo = New CDvdVideo()
  End Function
End Class

Class CCdAudio
  Implements IAudio

  Public Function GetSoundQuality() As String  _
            Implements IAudio.GetSoundQuality
      GetSoundQuality = "CD Audio is better then DVD Audio"
  End Function
End Class

Class CCdVideo
    Implements IVideo

    Public Function GetPictureQuality() As String _
                    Implements IVideo.GetPictureQuality
        GetPictureQuality = "CD video quality is not as good as DVD"
    End Function
End Class

Class CDvdAudio
    Implements IAudio

    Public Function GetSoundQuality() As String _ 
                        Implements IAudio.GetSoundQuality
        GetSoundQuality = "DVD Audio is not as good as CD Audio"
    End Function
End Class

Class CDvdVideo
    Implements IVideo

    Public Function GetPictureQuality() As String _ 
                 Implements IVideo.GetPictureQuality
        GetPictureQuality = "DVD video quality is better then CD"
    End Function
End Class

Public Class CAVMaker
    Public Function AVMake(ByVal xWhat As String) As IAVDevice
        Select Case xWhat.ToLower
            Case "cd"
                AVMake = New CCd()
            Case "dvd"
                AVMake = New CDvd()
        End Select
    End Function
End Class

public Class Client
	Public Shared Sub Main(ByVal CmdArgs() As String) 
		Dim objFactMaker As New CAVMaker()
		Dim objFact As IAVDevice
		Dim objAudio As IAudio
		Dim objVideo As IVideo
		Dim strWhat as String
		strWhat = CmdArgs(0)
		objFact = objFactMaker.AVMake(strWhat)
	        objAudio = objFact.GetAudio
        	objVideo = objFact.getVideo
	        Console.WriteLine(objAudio.GetSoundQuality)
        	Console.WriteLine(objVideo.GetPictureQuality)
	End sub
End Class

About the Author

Ashish works as a Sr. Software Developer with Lexign Inc., an end-to-end trusted electronic transaction management software provider (http://www.lexign.com). Ashish has six years of experience in designing and developing distributed systems, server technologies and web based software applications using Microsoft technologies, Java, XML and DOT Net. He holds MCSD (Microsoft Certified Software Developer) and SCJP (Sun Certified Java Programmer) certifications. Ashish Jaiman.

Downloads

Download demo project - 2 Kb


Comments

  • wheloltabotly PumeSonee Phobereurce 4103889

    Posted by TizefaTaNaday on 06/14/2013 08:00am

    TeednoffWob cheapshoesjordan.holidaygiving.org neorttriend airjordanxiretrowhitecolumbiablueblack.holidaygiving.org TypeAppeags

    Reply
  • Creational Pattern Abstract Factory

    Posted by Hamarnath.S.D on 05/29/2013 06:09am

    Thank you, After long search , a great article on abstract factory.It gave clear idea about abstract factory. keep posting......

    Reply
  • transcoding

    Posted by san123 on 03/13/2007 02:13am

    please send me some codes about transcoding (audio,video and image)under .net platform thank you. and please mail me

    Reply
  • Index out of range exception

    Posted by shashwat_c on 01/23/2007 12:58am

    The C# code gives index out of range exception at strWhat = args[0];do you know why?

    • transcoding

      Posted by abhimsin on 04/08/2012 10:08am

      Use strWhat = Console.ReadLine();

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds