Порождающие шаблоны проектирования


Реализация шаблона на базе выделенного класса-фабрики



бет14/15
Дата01.10.2022
өлшемі254,47 Kb.
#41019
1   ...   7   8   9   10   11   12   13   14   15

Реализация шаблона на базе выделенного класса-фабрики


Диаграмма классов:

Рисунок 12 Пример реализации шаблона «Прототип» на базе выделенного класса - фабрики
Исходный код:
public abstract class Warrior
{
public abstract Warrior Clone();
public abstract string Info();
}

public class Infantryman : Warrior


{
private static Infantryman _prototype = new Infantryman();
private Infantryman() { }
public override Warrior Clone()
{
Infantryman infantryman = new Infantryman();
return infantryman;
}
public override string Info() { return "Infantryman"; }
public static Infantryman Prototype
{
get { return _prototype; }
set { _prototype = value; }
}
}

public class Archer : Warrior


{
private static Archer _prototype = new Archer();
private int _arrousCount = 0;
private Archer(int parArrowsCount) { _arrowsCount = parArrowsCount; }
public override Warrior Clone()
{
Archer archer = new Archer();
archer._arrousCount = this._arrousCount;
return archer;
}
public override string Info() { return "Archer"; }
public static Archer Prototype
{
get { return _prototype; }
set { _prototype = value; }
}
}

public class Horseman : Warrior


{
private static Horseman _prototype = new Horseman();
private Color _horseColor;
private Horseman(Color parHorseColor) { _horseColor = parHorseColor; }
public override Warrior Clone()
{
Horseman horseman = new Horseman();
horseman._horseColor = this._horseColor;
return horseman;
}
public override string Info() { return "Horseman"; }
public static Horseman Prototype
{
get { return _prototype; }
set { _prototype = value; }
}
}

public class PrototypeFactory


{
public static Warrior CreateInfantryman()
{
return Infantryman.Prototype.Clone();
}
public static Warrior CreateArcher()
{
return Archer.Prototype.Clone();
}
public static Warrior CreateHorseman()
{
return Horseman.Prototype.Clone();
}
}
Пример использования:
// Настройка прототипов
Infantryman infantryman = new Infantryman();
Infantryman.Prototype = infantryman;
Archer archer = new Archer(20);
Archer.Prototype = archer;
Horseman horseman = new Horseman(Color.Black);
Horseman.Prototype = horseman;

// Использование настоенных прототипов


List army = new List();
army.Add(PrototypeFactory.CreateInfantryman());
army.Add(PrototypeFactory.CreateArcher());
army.Add(PrototypeFactory.CreateHorseman());
В приведенной реализации, для упрощения кода, реестр прототипов не ведется. Воины всех родов войск создаются при помощи соответствующих методов фабричного класса PrototypeFactory.


Достарыңызбен бөлісу:
1   ...   7   8   9   10   11   12   13   14   15




©emirsaba.org 2024
әкімшілігінің қараңыз

    Басты бет