Click here to Skip to main content
15,885,947 members
Articles / Programming Languages / C#
Tip/Trick

Implementing Factory Method in C#

Rate me:
Please Sign up or sign in to vote.
4.62/5 (12 votes)
14 Feb 2012CPOL1 min read 58.5K   5   8
Decoupling creation of objects from the client

Factory Method


Factory method is a widely used mechanism for creating instances of classes in any object oriented programming language. The Factory method abstracts the creation of objects from the consumer. It also provides a single place where objects can be created. I supplied the desired objects hiding the complexity of creation for the consumers.

Advantages of Factory Method



  1. Hides the complexity of creation from the consumer.
  2. Ensures the object creation logic to be in a single place
  3. Helps customise creation without disturbing the consumer logic
  4. Brings in logical separation between creation and usage

I have used a simple CarFactory example to demonstrate the same. The Factory manufactures swift cars of 2 types basic and featured with 3 different colors black, blue and red.

Steps for implementing the Factory Method



  1. Create an abstract class Swift Car with an attribute color and a method CaliculatePrice as the price differs for different models:
    C#
    /// <summary>
       /// abstract class for swift car
       /// </summary>
       public abstract  class SwiftCar
       {
           /// <summary>
           /// color of the Swift car
           /// </summary>
           public CarColor Color { get; private  set; }
    
           protected SwiftCar(CarColor color)
           {
               this.Color = color;
           }
    
           /// <summary>
           /// function that calculates the price
           ///  of the swift car
           /// </summary>
           /// <returns></returns>
           public abstract float  CaliculatePrice( );
       }

  2. Create 2 derived classes For Basic Swift Car and Featured Swift Car:
    C#
    /// <summary>
    /// the basic swift car
    /// </summary>
    public class SwiftCarBasic:SwiftCar
    {
        /// <summary>
        /// creates a basic swift car of defined color
        /// </summary>
        /// <param name="color">the color requested by the client</param>
        public SwiftCarBasic(CarColor color):base(color )
        {
    
        }
        /// <summary>
        /// customised calculation of price
        /// </summary>
        /// <returns> the price of the basic model of swift car</returns>
        public override float CaliculatePrice()
        {
            float BasicPrice = 400000F;
            return BasicPrice;
        }
    }
    
    /// <summary>
    /// The swift car with additional features
    /// </summary>
    public class SwiftCarFeatured : SwiftCar
    {
        /// <summary>
        /// Creates a Featured swift car with a color requested by the client
        /// </summary>
        /// <param name="Color">the color of the featured swift car</param>
        public SwiftCarFeatured(CarColor Color):base(Color )
        {
    
        }
        /// <summary>
        /// customised calculation of the car with additional features such as airbags,speakers power window etc
        /// </summary>
        /// <returns></returns>
        public override float CaliculatePrice()
        {
            float basicPrice = 400000F;
            float otherEquipmentCosts= 200000F;
            return  basicPrice +otherEquipmentCosts ;
        }
    }

  3. Define Enumerations which describe the Car types and Car colors
    C#
    /// <summary>
        /// The different types of Swift Car
        /// </summary>
        public enum SwiftCarType
        {
            /// <summary>
            /// basic model of Swift car
            /// </summary>
            BASIC,
             /// <summary>
            /// Advanced model of swift car
            /// </summary>
            FEATURED
        }
        /// <summary>
        /// the car color types
        /// </summary>
        public enum CarColor
        {
            BLACK,
            RED,
            BLUE
        }

  4. Create a static class with a static method which returns the Car of desired Type.
    Note: It is very important to keep the abstract base class Swift car as a Return Type.
    C#
    /// <summary>
        /// The Class represents the Factory of the Swift Car
        /// </summary>
        public static class SwiftCarFactory
        {
            /// <summary>
            /// The method creates a swift car as desired by the consumer
            /// </summary>
            /// <param name="carType"> the car type specified by the Consumer</param>
            /// <param name="carColor"> the color  of the car specified by the consumer </param>
            /// <returns> the desired swift car</returns>
            public static SwiftCar CreateSwiftCar(SwiftCarType carType, CarColor carColor)
            {
                SwiftCar car = null;
    
                switch (carType)
                {
                    case SwiftCarType.BASIC: car = new SwiftCarBasic(carColor);
                        break;
                    case SwiftCarType.FEATURED: car = new SwiftCarFeatured(carColor);
                        break;
                }
                return car;
            }
        }

  5. Design a Client to consume the Car from the Swift Car Factory.
    /// <summary>
       /// Client to Consume a Swift Car from the Swift Car Factory
       /// </summary>
        class ClientClass
        { 
            public static void Main(string[] args)
            {           
                //the basic Swift car of Blue color -Creation
                SwiftCar BlueBasicSwiftCar = SwiftCarFactory.CreateSwiftCar(SwiftCarType.BASIC, CarColor.BLUE);
               
                //Computation of Price
                float BlueBasicSwiftCarPrice = BlueBasicSwiftCar.CaliculatePrice();
                Console.WriteLine("price of Blue Basic Swift car" + BlueBasicSwiftCarPrice);
    
                //the Red Featured Swift car of Blue color -Creation
                SwiftCar RedFeaturedSwiftCar = SwiftCarFactory.CreateSwiftCar(SwiftCarType.FEATURED, CarColor.RED);
              
                // Computation of Price
                float RedFeaturedSwiftCarPrice = RedFeaturedSwiftCar.CaliculatePrice();
                Console.WriteLine("price of  Red Featured Swift car" + RedFeaturedSwiftCarPrice );   
            }
        }

Finally, it can be observed that creation logic is unknown to the client and since the factory takes care of the creation, the Factory logic can be further customised or changed easily.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
you could also follow up my articles on my personal blog

www.sanathshenoy.blogspot.com

Comments and Discussions

 
QuestionSimple Factory Pin
daveamour21-Dec-15 18:28
daveamour21-Dec-15 18:28 
AnswerRe: Simple Factory Pin
Member 1103633819-Jun-16 19:51
Member 1103633819-Jun-16 19:51 
GeneralRe: Simple Factory Pin
Pankaj Kumar29-Sep-16 2:13
Pankaj Kumar29-Sep-16 2:13 
GeneralVery good article Pin
zzfima11-Nov-13 8:56
zzfima11-Nov-13 8:56 
GeneralMy vote of 5 Pin
dpalash9-Mar-13 23:40
professionaldpalash9-Mar-13 23:40 
GeneralGood Article Pin
Rohith Gopi28-Jan-13 20:15
Rohith Gopi28-Jan-13 20:15 
QuestionWhat is use of creating SwiftCarFactory class? Pin
Jagz W29-Sep-12 19:14
professionalJagz W29-Sep-12 19:14 
AnswerRe: What is use of creating SwiftCarFactory class? Pin
Rohith Gopi28-Jan-13 20:21
Rohith Gopi28-Jan-13 20:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.