如何将对类属性的访问限制为仅在同一名称空间内
如何将对类属性的访问限制在同一命名空间内?考虑下面的课程。 Content 类无法 Publish 自身,而是 ContentService 类 在将状态更改为已发布之前将执行一些操作。
public class Content : Entity, IContent
{
public string Introduction { get; set; }
public string Body { get; set; }
public IList<Comment> Comments { get; set; }
public IList<Image> Images { get; private set; }
public State Status { get; }
}
public class ContentService
{
public IContent Publish(IContent article)
{
//Perform some biz rules before publishing
article.Status = State.Published;
return article;
}
}
我怎样才能做到只有 ContentService 类才能更改文章的状态?
有什么设计模式可以帮助我处理这个问题吗?
How do restrict access to a class property to within the same namespace? Consider the following class. The Content class cannot Publish itself, instead the ContentService class
will do a few things before changing the state to published.
public class Content : Entity, IContent
{
public string Introduction { get; set; }
public string Body { get; set; }
public IList<Comment> Comments { get; set; }
public IList<Image> Images { get; private set; }
public State Status { get; }
}
public class ContentService
{
public IContent Publish(IContent article)
{
//Perform some biz rules before publishing
article.Status = State.Published;
return article;
}
}
How can i make it so only the ContentService class can change the state of the article?
Are there any deisng patterns to help me deal with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用“内部”访问修饰符,以便只有同一程序集中的类可以修改 Content 类的 State 成员(但即使是其他程序集中的每个人都可以获取该值)。
所以现在 ContentService 可以设置状态,因为它位于同一个 Assembly 中,但外部调用者只能获取状态(不允许他们设置它)。
You can use the "internal" access modifier so that only classes within the same Assembly can modify the Content class's State member (but everyone even in other assemblies can GET the value).
So now ContentService can set the state because it is in the same Assembly, but outside callers can only get the state (they're not allowed to set it).
Java 有“包可见”或“包私有”的概念。事实上,这是您未指定可见性(
private
或public
)的任何内容的默认设置。由于某种原因,几乎没有人使用过它。Java has the notion of "package visible" or "package private". This is in fact the default for anything where you don't specify a visibility (
private
orpublic
). For some reason, almost no one ever uses this.将 ContentService 声明为朋友?
或者,Java 有一个 访问修饰符,相当于“包私有”。
Declare ContentService as a friend?
Alternatively, Java has an access modifier that amounts to "package-private".