nzdev
nzdev

Reputation: 334

How to implement factory design pattern in WCF with this example?

I am new to WCF and new to factory design pattern. How do you actually implement a factory design pattern in this example?

I have created 4 classes addition, subtraction, multiplication and division in the project so if there is a way to call those classes to perform the calculation other than doing calculation in the interface that will be great.

Thanks in advance.

[OperationContract]
int Calculation(int value1, int value2, string calType);

public class Service1 : IService1
{
   public int Calculation(int value1, int value2, string calType) 
   {
        try {
            switch (calType)
            {
                case "addition":
                    return value1 + value2;

                case "subtraction":
                    return value1 - value2;

                case "multiplication":
                    return value1 * value2;
                case "division":
                    return value1 / value2;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        return 0;
     }
  }

Upvotes: 0

Views: 2614

Answers (1)

Rohan M Nabar
Rohan M Nabar

Reputation: 83

ok lets do this , factory pattern in wcf

we take a classic shape example , by implementing factory pattern we can effectively reduce the code in service class

only shape factory class needs to be in WCF service class , rest can have their own business class

1) create an interface

 public interface Shape {
 void  draw();
 }

2) create classes like this

public class Rectangle : Shape {

 public void draw() {
 print("Inside Rectangle::draw() method.");
  }
  }

public class Square : Shape {

  public void draw() {
  print("Inside Square::draw() method.");
  }
  }

3) Now have a service factory class

 [service contract]
  public class ShapeFactory {

 //use getShape method to get object of type shape 

  [operation contract]
  public Shape getShape(String shapeType){
  if(shapeType == null){
     return null;
  }     
  if(shapeType.equalsIgnoreCase("CIRCLE")){
     return new Circle();
  } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
     return new Rectangle();
  } else if(shapeType.equalsIgnoreCase("SQUARE")){
     return new Square();
  }
  return null;
  }
  }

and expose this method in Interface of your service

4)let the client do the rest

Code is to provide general idea

factory pattern may have great implementation in wcf

Upvotes: 1

Related Questions