Абстрактная фабрика (Abstract Factory)
Материал из Вики ИТ мехмата ЮФУ
Назначение
Предоставляет интерфейс для создания компонентов системы.
Другое название
Инструментарий (Kit)
Описание
Использование
Реализация
Диаграмма классов
Участники
Код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MazeCommon;
namespace MazeGameAbstractFactory
{
public class MazeFactory
{
public virtual Maze MakeMaze()
{
return new Maze();
}
public virtual Wall MakeWall()
{
return new Wall();
}
public virtual Room MakeRoom(int n)
{
return new Room(n);
}
public virtual Door MakeDoor(Room r1, Room r2)
{
return new Door(r1,r2);
}
};
public class MazeGame
{
public Maze CreateMaze(MazeFactory f)
{
Maze aMaze = f.MakeMaze();
Room r1 = f.MakeRoom(1);
Room r2 = f.MakeRoom(2);
Door d = f.MakeDoor(r1,r2);
aMaze.AddRoom(r1);
aMaze.AddRoom(r2);
r1.SetSide(Direction.North, f.MakeWall());
r1.SetSide(Direction.East, d);
r1.SetSide(Direction.South, f.MakeWall());
r1.SetSide(Direction.West, f.MakeWall());
r2.SetSide(Direction.North, f.MakeWall());
r2.SetSide(Direction.East, f.MakeWall());
r2.SetSide(Direction.South, f.MakeWall());
r2.SetSide(Direction.West, d);
return aMaze;
}
}
public class BombedWall: Wall
{
public override object Clone()
{
return new BombedWall();
}
}
public class RoomWithABomb: Room
{
public RoomWithABomb(int n): base(n)
{ }
public override object Clone()
{
return new RoomWithABomb(this.RoomNumber);
}
}
public class BombedMazeFactory : MazeFactory
{
public override Room MakeRoom(int n)
{
return new RoomWithABomb(n);
}
public override Wall MakeWall()
{
return new BombedWall();
}
};
public class ProgramAbstractFactory
{
static void Main(string[] args)
{
Console.WriteLine("AbstractFactory");
MazeGame game = new MazeGame();
BombedMazeFactory f = new BombedMazeFactory();
game.CreateMaze(f);
}
}
}