简体   繁体   English

强制不变性并在接口声明中创建实例

[英]Force immutability and create instance in the interface declaration

I have an interface that its API are only getter methods thereby ensuring that the class that implements the interface is in that respect immutable. 我有一个接口,其API只是getter方法,从而确保实现接口的类在这方面是不可变的。
But if I need to update something that changes the behavior of the interface how would I declare my interface so that it creates a new instance of the concrete class? 但是如果我需要更新改变接口行为的东西,我将如何声明我的接口以便创建具体类的新实例?
Right now I have something like: 现在我有类似的东西:

    public interface Generator {  
      public int[] values();  
      public float[] indications();  
      //etc  
      public MyEnum type;  
    }  

    public class ConcreteClass implements Generator {  
      private ConcreteClass() {  
      }  
      public static ConcreteClass createInstance() {  

       }  
   }    

I have omitted arguments for clarity. 为清楚起见,我省略了论据。
How would I move the createInstance to the interface? 如何将createInstance移动到界面?

An interface is not designed to have implementation. 接口不是为实现而设计的。 With Java 8 you could have default method but it would be a bad idea that interface knows the implementation classes. 使用Java 8,您可以使用默认方法,但接口知道实现类是个坏主意。 An interface should stay abstract and not know its subclasses. 接口应该保持抽象,不知道它的子类。

If ConcreteClass is immutable, you should document it and ensure that each method with side-effect doesn't apply any modification on the current object but instead create a new instance of ConcreteClass . 如果ConcreteClass是不可变的,您应该记录它并确保每个带有副作用的方法不对当前对象应用任何修改,而是创建一个新的ConcreteClass实例。

For example suppose you want provide method to update the values field, you could provide this method in ConcreteClass : 例如,假设您想要提供方法来更新values字段,您可以在ConcreteClass提供此方法:

public ConcreteClass withValues(int[] values){
   // copy all existing properties from the original to the copy but values
   ConcreteClass copy = new ConcreteClass(values, this.indications, this.type);    
   return copy;
}

If you want really move out the instance creation from ConcreteClass , you could create a factory that provides this service. 如果您想真正从ConcreteClass移出实例创建,您可以创建一个提供此服务的工厂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM