Factory method pattern: Difference between revisions

Content deleted Content added
Tag: Reverted
Line 75:
<syntaxhighlight lang="csharp">
// Empty vocabulary of actual object
public interface IPersonIPerso
{
string GetName();
}
 
public class Villager : IPerson
{
public string GetName()
{
return "Village Person";
}
}
 
public class CityPerson : IPerson
{
public string GetName()
{
Line 113 ⟶ 99:
case PersonType.Rural:
return new Villager();
case PersonType.Urban:
return new CityPerson();
default:
throw new NotSupportedException();
}
}
}
</syntaxhighlight>
In the above code you can see the creation of one interface called <code>IPerson</code> and two implementations called <code>Villager</code> and <code>CityPerson</code>. Based on the type passed into the <code>Factory</code> object, we are returning the original concrete object as the interface <code>IPerson</code>.
 
A factory method is just an addition to <code>Factory</code> class. It creates the object of the class through interfaces but on the other hand, it also lets the subclass decide which class is instantiated.
 
<syntaxhighlight lang="csharp">
public interface IProduct
{
string GetName();
bool SetPrice(double price);
}
Line 155 ⟶ 126:
public IProduct GetObject() // Implementation of Factory Method.
{
{
return this.MakeProduct();
}
}
 
public class PhoneConcreteFactory : ProductAbstractFactory
{
protected override IProduct MakeProduct()
{
IProduct product = new Phone();
// Do something with the object after you get the object.
product.SetPrice(20.30);
return product;
}
Line 179 ⟶ 140:
<syntaxhighlight lang="java">
public abstract class Room {
rooms.add(room1);
abstract void connect(Room room);
}
 
public class MagicRoom extends Room {
public void connect(Room room) {}
}
 
public class OrdinaryRoom extends Room {
public void connect(Room room) {}
}
 
public abstract class MazeGame {
private final List<Room> rooms = new ArrayList<>();
 
public MazeGame() {
Room room1 = makeRoom();
Room room2 = makeRoom();
room1.connect(room2);
rooms.add(room1);
rooms.add(room2);
}
Line 205 ⟶ 148:
</syntaxhighlight>
 
In the above snippet, the
In the above snippet, the <code>MazeGame</code> constructor is a [[Template method pattern|template method]] that makes some common logic. It refers to the <code>makeRoom</code> factory method that encapsulates the creation of rooms such that other rooms can be used in a subclass. To implement the other game mode that has magic rooms, it suffices to override the <code>makeRoom</code> method:
 
<syntaxhighlight lang="java">
public class MagicMazeGame extends MazeGame {
@Override
protected MagicRoom makeRoom() {
return new MagicRoom();
}
}