2017-01-27 40 views
0

进行我有下面的类:构造一类,其超只能通过工厂方法

public class Foo(){ 
    int parameter; 
    static Set<Foo> cache=new HashSet<Foo>(); 
    public Foo(int parameter){ 
     this.parameter=parameter; 
     addToCache(this); 
    } 
    public static Foo Factory(int parameter){ 
     Foo duplicate=findDuplicate(parameter); 
     if (duplicate!=null){ 
      return duplicate; 
     }else{ 
      return new Foo(parameter); 
     } 
    } 
} 

注意,调用Foo的构造将直接加入到静态缓存。 我现在需要继承这个对象来添加一些功能。

public class Bar() extends Foo{ 
    public Bar(int parameter){ 
     //Danger 
    } 
} 

但现在我卡住了。酒吧的构造函数必须以某种方式致电super(),但不会检查像Foo.Factory()这样的重复项。

我真的想会是什么这样的:

public Bar(int parameter){ 
    this=Foo.Factory(parameter); 
} 

但是,这显然不是有效的Java。

现在,我已经被迫写美孚也检查重复哈克次级构造,并酒吧使用:

//Second unused parameter just so the constructors are different 
public Foo(int parameter, boolean isEvil){ 
    Foo duplicate= findDuplicate(parameter); 
    if (duplicate!=null){ 
     this.copy(duplicate); //Evilly take on all attributes of duplicate 
    }else{ 
     //Now we have to copy the body of the original constructor. 
     //It has to be kept synched forever, and I can't even call it! 
     this.parameter=parameter; 
     addToCache(this); 
    } 
} 

Bar(int parameter){ 
    super(int,true); 
} 

但这始终创建新对象的问题,这可能会导致可变性和散列问题。此外,任何不注意的人都不能说这个构造函数的工作方式不同。

TLDR:如何为超类只能通过工厂方法创建类的构造函数。

this question可能的复制,但在Java中(也即问题只有一个答案,这是不令人满意的,以我和OP)

+1

如果只能通过工厂方法创建超类,那么只能通过工厂方法创建子类。因为子类的成员是超类的成员。 –

回答

1

我看到它的方式,你有两个选择。

选项1是为bar而不是公共构造函数创建工厂方法。

选项2是,代替使bar继承自foo,而代之以foo作为成员的实例。在构造函数中,您可以调用foo的工厂方法。

你走哪条路可能取决于细节。

相关问题