xxxxxxxxxx
public interface IShape
{
void Draw();
}
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
public class Square : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a square.");
}
}
public class ShapeFactory
{
public IShape CreateShape(string shapeType)
{
if (shapeType.Equals("Circle", StringComparison.OrdinalIgnoreCase))
{
return new Circle();
}
else if (shapeType.Equals("Square", StringComparison.OrdinalIgnoreCase))
{
return new Square();
}
else
{
throw new ArgumentException("Invalid shape type.");
}
}
}
xxxxxxxxxx
from abc import ABC, abstractmethod
class MazeGame(ABC):
def __init__(self) -> None:
self.rooms = []
self._prepare_rooms()
def _prepare_rooms(self) -> None:
room1 = self.make_room()
room2 = self.make_room()
room1.connect(room2)
self.rooms.append(room1)
self.rooms.append(room2)
def play(self) -> None:
print(f"Playing using {self.rooms[0]}")
@abstractmethod
def make_room(self):
raise NotImplementedError("You should implement this!")
class MagicMazeGame(MazeGame):
def make_room(self) -> "MagicRoom":
return MagicRoom()
class OrdinaryMazeGame(MazeGame):
def make_room(self) -> "OrdinaryRoom":
return OrdinaryRoom()
class Room(ABC):
def __init__(self) -> None:
self.connected_rooms = []
def connect(self, room: "Room") -> None:
self.connected_rooms.append(room)
class MagicRoom(Room):
def __str__(self) -> str:
return "Magic room"
class OrdinaryRoom(Room):
def __str__(self) -> str:
return "Ordinary room"
ordinaryGame = OrdinaryMazeGame()
ordinaryGame.play()
magicGame = MagicMazeGame()
magicGame.play()
xxxxxxxxxx
Factory pattern
- a DP (design pattern) that may be the chosen solution approach by an app architect.
- there are factory functions and there are factory classes.
- - A factory class could be used to return a customized object (based on args)
In terms of code readability, factory pattern reveals the exact nature of the new object
we are creating. Also using this DP makes it easier to organize back-end development.