- Get link
- X
- Other Apps
Following is an example of the Factory Method. In this case, a method call sets and returns the type. Also, pardon the values set as field, rather than as properties, but this is a simple example, rather than a full implementation.
Salient Point(s)
Code
using System;
namespace DesignPatterns
{
//primary class for factory method
public class FactoryObject
{
//public fields, set as part of method and return
public int X;
public int Y;
public int Result;
//factory method
public FactoryObject Addition(int x, int y)
{
return new FactoryObject(x, y, x + y);
}
//factory method
public FactoryObject Subtaction(int x, int y)
{
return new FactoryObject(x, y, x - y);
}
//factory method
public FactoryObject Multiplication(int x, int y)
{
return new FactoryObject(x, y, x * y);
}
//factory method
public FactoryObject Division(int x, int y)
{
return new FactoryObject(x, y, (y == 0) ? 0 : (x / y));
}
//constructor is private
//object is returned via factory methods
private FactoryObject(int x, int y, int result)
{
this.X = x;
this.Y = y;
this.Result = result;
}
}
}
Salient Point(s)
- A hidden constructor
- Each class method instantiates the class differently.
Code
using System;
namespace DesignPatterns
{
//primary class for factory method
public class FactoryObject
{
//public fields, set as part of method and return
public int X;
public int Y;
public int Result;
//factory method
public FactoryObject Addition(int x, int y)
{
return new FactoryObject(x, y, x + y);
}
//factory method
public FactoryObject Subtaction(int x, int y)
{
return new FactoryObject(x, y, x - y);
}
//factory method
public FactoryObject Multiplication(int x, int y)
{
return new FactoryObject(x, y, x * y);
}
//factory method
public FactoryObject Division(int x, int y)
{
return new FactoryObject(x, y, (y == 0) ? 0 : (x / y));
}
//constructor is private
//object is returned via factory methods
private FactoryObject(int x, int y, int result)
{
this.X = x;
this.Y = y;
this.Result = result;
}
}
}
Comments
Post a Comment