与 Dependency Injection 的良好旧关联如何(因此您可以稍后在需要时更改它以允许其他类访问这些函数)。
public class Parent {
private PrivilegedFunctions p;
public Parent(PrivilegedFunctions inP) { p = inP; }
}
public interface PrivilegedFunctions {
void SomeFuncHere();
}
public class AllowPrivileges : PrivilegedFunctions {
public void AllowPrivileges () { }
public void SomeFuncHere()
{
// Actual implementation
}
}
public class NoPrivileges : PrivilegedFunctions {
public void NoPrivileges () { }
public void SomeFuncHere()
{
// No implementation
}
}
public class Child1 : Parent {
public Child1(PrivilegedFunctions inP) : base(inP) { }
}
然后根据 Child,您可以注入AllowPrivileges
orNoPrivileges
版本。
// Child with privileges
Child1 with_priv = new Child1(new AllowPrivileges());
with_priv.SomeFuncHere(); // Does privileged operation
// Child without privileges
Child1 without_priv = new Child1(new NoPrivileges());
without_priv.SomeFuncHere(); // Does nothing