![](/user_photo/1642_T3gTB.jpg)
Ответы к экзамену 0
.4.pdf![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB31x1.jpg)
Шаблон делегирования – это способ, которым объект внешне выражает некоторое поведение, но в реальности передаёт ответственность за выполнение этого поведения связанному объекту.
Шаблон даёт возможность изменить поведение конкретного экземпляра объекта вместо создания нового класса путем наследования. Таким образом, если при работе с объектом велика вероятность возникновения такой ситуации, следует использовать шаблон делегирования.
Шаблон реализуется следующим образом:
using System; using System.Text;
interface IDelegate
{
double sum(double a, double b);
}
class GoodStudent : IDelegate
{
public double sum(double a, double b) { return a + b; }
}
class BadStudent : IDelegate
{
public double sum(double a, double b)
{
Random rand = new Random(); return rand.Next(5, 10);
}
}
class Delegate : IDelegate
{
IDelegate student = new GoodStudent();
public double sum(double a, double b)
{
return student.sum(a, b);
}
public void setStudent(IDelegate s)
{
student = s;
}
}
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB32x1.jpg)
class Program
{
static void Main(string[] args)
{
Delegate teacher = new Delegate();
Console.WriteLine("Хороший студент: 2 + 2 = " + teacher.sum(2, 2));
teacher.setStudent(new BadStudent());
Console.WriteLine("Плохой студент: 2 + 2 = " + teacher.sum(2, 2));
Console.ReadLine();
}
}
using System; using System.Text;
public interface IImmutable
{
bool isImmutable { get; } void makeImmutable();
}
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB33x1.jpg)
public abstract class Immutable : IImmutable
{
private bool immutable;
public bool isImmutable
{
get
{
return immutable;
}
}
public virtual void makeImmutable()
{
immutable = true;
}
protected virtual void checkImmutable()
{
if (immutable) throw new Exception("[Error] Нельзя менять свойства неизменяемых объектов");
}
}
public class Planet : Immutable
{
private string name; private double mass; private double g;
public string Name
{
get { return name; }
set { checkImmutable(); name = value; }
}
public double M
{
get { return mass; }
set { checkImmutable(); mass = value; }
}
public double G
{
get { return g; }
set { checkImmutable(); g = value; }
}
public Planet(string name, double M, double g)
{
this.name = name; this.mass = M; this.g = g;
makeImmutable();
}
}
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB34x1.jpg)
#include <stdio.h> #include <tchar.h>
#define interface struct
interface IObject
{
public:
virtual void Draw() = 0;
};
class Triangle : IObject
{
public: Triangle(){}; void Draw()
{
printf("рисуется треугольник");
};
};
class Plane : IObject
{
public: Plane(){}; void Draw()
{
printf("рисуется плоскость");
};
};
int _tmain(int argc, _TCHAR* argv[])
{
Plane *plane = new Plane(); plane->Draw();
getchar(); return 0;
}
interface IMathExceptionMarker { }
abstract class MyException
{
public string Message;
}
class DivException : MyException, IMathExceptionMarker
{
public DivException() { Message = "Деление на ноль!"; }
}
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB35x1.jpg)
class OverflowException : MyException
{
public OverflowException() { Message = "Переполнение стека"; }
}
class LgException : MyException, IMathExceptionMarker
{
public LgException()
{
Message = "lg(x), x > 0!!";
}
}
class Program
{
static void Main(string[] args)
{
List<MyException> exceptions = new List<MyException>();
exceptions.Add(new DivException()); exceptions.Add(new OverflowException()); exceptions.Add(new LgException());
foreach (MyException e in exceptions)
{
if(!(e is IMathExceptionMarker)) Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
using System;
using System.Collections.Generic; using System.Text;
namespace Patterns
{
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB36x1.jpg)
public interface IPropertyContainer
{
void SetProperty(string name, object value); void RemoveProperty(string name);
object GetProperty(string name); List<String> GetAllPropertiesNames();
}
public abstract class PropertyContainer:IPropertyContainer
{
protected Dictionary<string, object> Properties;
public PropertyContainer() {
Properties = new Dictionary<string, object>();
}
public PropertyContainer(Dictionary<string, object> prop) { this.Properties = prop;
}
public void SetProperty(string key, object value) { try {
Properties[key] = value;
}
catch(KeyNotFoundException){ Properties.Add(key,value);
}
}
public object GetProperty(string name) { try {
return Properties[name];
}
catch(KeyNotFoundException) { return null;
}
}
public void RemoveProperty(string name) { try
{
Properties.Remove(name);
}
catch (KeyNotFoundException)
{
}
}
public List<string> GetAllPropertiesNames() { return Properties.Keys.ToList();
}
public override string ToString()
{
string result= "";
foreach (KeyValuePair<string,object> kvp in this.Properties) {
result += kvp.Key + ": "+kvp.Value.ToString()+Environment.NewLine;
}
return result;
}
}
public enum PASTRY_TYPE {THIN, THICK, MIDDLE} public class PizzaContainer:PropertyContainer
{
public string Cheese
{
get { return (string)GetProperty("cheese"); } set
{
SetProperty("cheese", value);
}
}
public PASTRY_TYPE PastryType
{
get { return (PASTRY_TYPE)GetProperty("pastrytype"); } set { SetProperty("pastrytype", value); }
}
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB37x1.jpg)
public override string ToString()
{
string result = "Pizza Info:" + Environment.NewLine; result+=base.ToString();
return result;
}
}
class Program
{
static void Main(string[] args)
{
PizzaContainer pizza = new PizzaContainer(); pizza.Cheese = "Mozarella";
pizza.PastryType = PASTRY_TYPE.THICK; pizza.SetProperty("tomato",true); Console.WriteLine(pizza.ToString()); Console.ReadLine();
}
}
}
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB38x1.jpg)
using System; using System.Text;
abstract class Factory
{
public abstract AbstractProductA CreateProductA(); public abstract AbstractProductB CreateProductB();
}
class ConcreteFactory1 : Factory
{
public override AbstractProductA CreateProductA()
{
return new ProductA1();
}
public override AbstractProductB CreateProductB()
{
return new ProductB1();
}
}
class ConcreteFactory2 : Factory
{
public override AbstractProductA CreateProductA()
{
return new ProductA2();
}
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB39x1.jpg)
public override AbstractProductB CreateProductB()
{
return new ProductB2();
}
}
abstract class AbstractProductA { }
class ProductA1 : AbstractProductA { } class ProductA2 : AbstractProductA { }
abstract class AbstractProductB
{
public abstract void Interact(AbstractProductA a);
}
class ProductB1 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name + " взаимодействует с " + a.GetType().Name);
}
}
class ProductB2 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name + " взаимодействует с " + a.GetType().Name);
}
}
class Client
{
private AbstractProductA abstractProductA; private AbstractProductB abstractProductB;
public Client(Factory factory)
{
abstractProductB = factory.CreateProductB(); abstractProductA = factory.CreateProductA();
}
public void Run()
{
abstractProductB.Interact(abstractProductA);
}
}
class Program
{
static void Main(string[] args)
{
Factory factory1 = new ConcreteFactory1(); Client c1 = new Client(factory1); c1.Run();
Factory factory2 = new ConcreteFactory2(); Client c2 = new Client(factory2); c2.Run();
Console.Read();
}
}
![](/html/1642/141/html_WbZZiFzfBT.fNL6/htmlconvd-rh1vTB40x1.jpg)
using System;
using System.Collections.Generic; using System.Text;
public interface Mutator
{
void SetLegs(); void SetTail(); void SetSwim(); void SetRoar();
Pet GetPet();
}
public class Pet
{
public int legs; public bool tail;
public bool is_swimming; public string roar;
public void Roar()
{
Console.WriteLine(this.roar);
}
}