QFramework框架设计中的接口使用技巧(接口+静态拓展)
using UnityEngine;
namespace FrameworkDesign.Example
{
#region 规则定义
public class CanDoEverything
{
public void DoSomething1()
{
Debug.Log("DoSomething1");
}
public void DoSomething2()
{
Debug.Log("DoSomething2");
}
public void DoSomething3()
{
Debug.Log("DoSomething3");
}
}
public interface IHasEverything
{
CanDoEverything CanDoEverything { get; }
}
#region 第一套规则 可访问全功能类中的DoSomething1方法(具体类通过继承该接口并显式实现IHasEverything中的CanDoEverything属性)
public interface ICanDoSomething1 : IHasEverything
{
}
public static class ICanDoSomething1Extension
{
public static void DoSomething1(this ICanDoSomething1 self)
{
self.CanDoEverything.DoSomething1();
}
}
#endregion
#region 第二套规则 可访问全功能类中的DoSomething2方法(具体类通过继承该接口并显式实现IHasEverything中的CanDoEverything属性)
public interface ICanDoSomething2 : IHasEverything
{
}
public static class ICanDoSomething2Extension
{
public static void DoSomething2(this ICanDoSomething2 self)
{
self.CanDoEverything.DoSomething2();
}
}
#endregion
#region 第三套规则 可访问全功能类中的DoSomething2方法(具体类通过继承该接口并显式实现IHasEverything中的CanDoEverything属性)
public interface ICanDoSomething3 : IHasEverything
{
}
public static class ICanDoSomething3Extension
{
public static void DoSomething3(this ICanDoSomething3 self)
{
self.CanDoEverything.DoSomething3();
}
}
#endregion
#endregion
public class InterfaceRuleExample : MonoBehaviour
{
#region 使用规则
public class OnlyCanDo1 : ICanDoSomething1
{
CanDoEverything IHasEverything.CanDoEverything { get; } = new CanDoEverything();
}
public class OnlyCanDo23 : ICanDoSomething2, ICanDoSomething3
{
CanDoEverything IHasEverything.CanDoEverything { get; } = new CanDoEverything();
}
#endregion
private void Start()
{
OnlyCanDo1 do1 = new OnlyCanDo1();
do1.DoSomething1();
OnlyCanDo23 do23 = new OnlyCanDo23();
do23.DoSomething2();
do23.DoSomething3();
}
}
}