我制作了下面的示例,它使工厂能够打包具有功能的对象,但问题是功能与对象分离。
我的最终目标是附加功能,例如log,save和display,它们对每个不同对象的特定属性进行操作。
我将如何保留此示例的外部装饰方面,但启用诸如将对象数据保存到数据库的“保存”或记录其活动的“日志”之类的功能?
using System;
using System.Collections.Generic;
namespace FuncAdorn3923
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
ObjectFactory.Instance.AdornFunctionality(customer, "add");
Console.WriteLine(customer.CallAlgorithm("add", 64, 36));
Employee employee = new Employee();
ObjectFactory.Instance.AdornFunctionality(employee, "add");
ObjectFactory.Instance.AdornFunctionality(employee, "subtract");
Console.WriteLine(employee.CallAlgorithm("add", 5, 15));
Console.WriteLine(employee.CallAlgorithm("subtract", 66, 16));
Console.ReadLine();
}
}
public class ObjectFactory
{
private static ObjectFactory singleton;
public void AdornFunctionality(AdornedObject ao, string idCode)
{
Func<int, int, int> add = (i, j) => i + j;
Func<int, int, int> subtract = (i, j) => i - j;
switch (idCode)
{
case "add":
ao.LoadAlgorithm(idCode, add);
break;
case "subtract":
ao.LoadAlgorithm(idCode, subtract);
break;
}
}
public static ObjectFactory Instance
{
get
{
if (singleton == null)
singleton = new ObjectFactory();
return singleton;
}
}
}
public abstract class AdornedObject
{
private Dictionary<string, Func<int, int, int>> algorithms =
new Dictionary<string, Func<int, int, int>>();
public void LoadAlgorithm(string idCode, Func<int,int,int> func)
{
algorithms.Add(idCode, func);
}
public int CallAlgorithm(string idCode, int i1, int i2)
{
Func<int,int,int> func = algorithms[idCode];
return func.Invoke(i1, i2);
}
}
public class Customer : AdornedObject
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int NumberOfProductsBought { get; set; }
}
public class Employee : AdornedObject
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
}