在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方法来实现不同的设计模式。这些设计模式有助于提高代码的可维护性、可扩展性和封装性。