我正在阅读Josh Bloch的书" Effective Java",他建议在构建具有大量成员的对象时使用构建器设计模式.从我所看到的不是香草的设计模式,而是看起来像他的变化.我更喜欢它的外观,并试图在我正在编写的C#Web应用程序中使用它.这是用Java编写的代码并且工作得很好
public class Property {
private String title;
private String area;
private int sleeps = 0;
public static void main(String[] args) {
Property newProperty = new Property.Builder("Test Property").Area("Test Area").Sleeps(7).build();
}
private Property(Builder builder) {
this.title = builder.title;
this.area = builder.area;
this.sleeps =builder.sleeps;
}
public static class Builder{
private String title;
private String area;
private int sleeps = 0;
public Builder (String title){
this.title = title;
}
public Builder Area(String area){
this.area = area;
return this;
}
public Builder Sleeps(int sleeps){
this.sleeps = sleeps;
return this;
}
public Property build() {
return new Property(this);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我把它放入我认为是C#的等价物时
public class Property
{
private String title;
private String area;
private Property(Builder Builder)
{
title = Builder.title;
area = Builder.area;
}
public static class Builder
{
// Required parameters
private String title;
private String area;
// Optional parameters
private int sleeps = 0;
public Builder(String val)
{
this.title = val;
}
public Builder Area(String val)
{
this.area = val;
return this;
}
public Builder Sleeps(int val)
{
this.sleeps = val;
return this;
}
public Property build()
{
return new Property(this);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我得到编译器警告.他们中的大多数"无法在静态类中声明实例成员".
所以我的问题首先是我错过了什么?如果我错过了某些东西,我可以按照Josh Bloch推荐的方式进行,但是在C#中,最后,这一点也很重要,这是线程安全吗?
Joa*_*uer 13
public static class
在Java中意味着您定义了一个静态嵌套类.这意味着它在逻辑上包含在另一个类中,但它的实例可以存在而不引用它的外部类.非静态嵌套类称为"内部类",它的实例只能存在于外部类的实例中.
在C#中,a static class
是无法实例化的,因此不能拥有任何非静态成员.在Java中没有与此构造等效的直接语言级别,但您可以通过仅提供私有构造函数来轻松地防止Java类的实例化.
简短的Java回顾:
static
称为内部类static
嵌套类没有单独的名称static
嵌套类在很大程度上独立于其外部类(某些特权访问除外).如果一些C#guru告诉我们如何在C#/ .NET中处理内部/嵌套类,我会很高兴.
我认为,如果您将 Builder 创建为顶级类(这正是 Java 中的内容)并创建一个工厂方法来接收构建器以保持构造函数私有(这反过来又会),则可以实现几乎相同的效果如果需要,让您返回子类实例)。
重点是让构建器执行创建对象所需的步骤。
所以(如果你不太了解 C#,你可以尝试这样的事情)
// My naive C# attempt:P
public class Property
{
public static void main( String []args )
{
Property p = Property.buildFrom( new Builder("title").Area("area").Etc() )
}
public static Property buildFrom( Builder builder )
{
return new Propert( builder );
}
private Property ( Builder builder )
{
this.area = builder.area;
this.title = builder.title;
// etc.
}
}
public class Builder
{
public Builder ( String t )
{
this.title = t;
}
public Builder Area( String area )
{
this.area = area;
return this;
}
// etc.
}
Run Code Online (Sandbox Code Playgroud)
将 Builder 作为属性的静态内部类的全部目的是在两者之间创建高度耦合(就好像它们是一个一样)。这就是为什么 Builder 中的 build 方法调用私有“Property”构造函数。
也许在 C# 中,您可以使用替代工件来创建相同的耦合。
归档时间: |
|
查看次数: |
737 次 |
最近记录: |