在C#中,Get和Set方法通常用于訪問和修改類的屬性。在設計模式中,這些方法的應用可以增強代碼的可維護性、可擴展性和封裝性。以下是一些設計模式在C#中Get和Set方法的應用示例:
public class Singleton
{
private static Singleton _instance;
private Singleton() { }
public static Singleton Instance
{
get { return _instance ?? (_instance = new Singleton()); }
}
}
public interface IProduct
{
void Use();
}
public class ConcreteProduct : IProduct
{
public void Use()
{
Console.WriteLine("Using ConcreteProduct");
}
}
public class ProductFactory
{
private static Dictionary<string, IProduct> _products = new Dictionary<string, IProduct>();
public static IProduct GetProduct(string key)
{
if (!_products.ContainsKey(key))
{
_products[key] = new ConcreteProduct();
}
return _products[key];
}
public static void SetProduct(string key, IProduct product)
{
_products[key] = product;
}
}
public interface ISubject
{
event EventHandler DataChanged;
void AddObserver(IObserver observer);
void RemoveObserver(IObserver observer);
}
public interface IObserver
{
void Update();
}
public class Subject : ISubject
{
private List<IObserver> _observers = new List<IObserver>();
private string _data;
public event EventHandler DataChanged;
public void AddObserver(IObserver observer)
{
_observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
_observers.Remove(observer);
}
public void SetData(string data)
{
_data = data;
DataChanged?.Invoke(this, EventArgs.Empty);
}
public string GetData()
{
return _data;
}
}
這些示例展示了如何在C#中使用Get和Set方法來實現不同的設計模式。這些設計模式有助于提高代碼的可維護性、可擴展性和封裝性。