0

拥有设置模型:

public class exampleclass
{
    private Something something;

    public Something getSomething()
    {
        return something;
    }

    public void setSomething(Something st)
    {
         something = st;
    }
}

我想做这样的事情:

public class exampleclass
{
    public Something something;

    public void setSomething(Something st)
    {
         something = st;
    }
}

但是我想在课堂之外拥有具有只读功能的“某物”var (但在自己的课堂中可重写)。关于如何为优化访问执行此操作的任何想法。(认为​​这将在 android 中使用,但使用纯 java only 框架(libgdx))

4

3 回答 3

3

You can set thoose things in constructor and expose public final field:

public class ExampleClass
{
    public final Something something;

    public ExampleClass(Something st)
    {
         something = st;
    }
}
于 2012-12-16T15:22:39.777 回答
0

You could use the final keyword. The you can assign it once.

e.g

public class Exampleclass
{
    public final Something something;
    void Exampleclass(Something init) {
        this.something = init;
    }
}

However the content of Something still could be changed, so you may consider returning a clone() of something. (see the class java.util.Date, you still could set the timestamp, in such cases only clone() or a copy constructor helps) . But if your code is not a public lib, then you can leav that getter with clone() away

public class Exampleclass
    {
        private Something something;
        void Exampleclass(Something init) {
            this.something = init;
        }
       void Something getSomething() {
            return something.clone();
        }

    }

But that depends on Something. Another soultion is a Factory Pattern, such that only the Factory can create Something. Then there is no public constructor in Something. Only the factory can create it.

public class Something() {
   private int value;
   protectectd Something(int value) {
      this.value = value;
   }
   public tostring() {
      System.out.println("values = " + value);
   }
}
public class SomethingFactory() {
  protected static Someting createSomething(int value)  {
     return new Something(value);   
 }
}

USage:

Something some = SomethingFactory.createSomething(3);

But read more by search "java Deisgn Patterns Factory" or FactoryPattern

于 2012-12-16T15:22:29.183 回答
0

我猜你的问题是转义引用,如果你想在返回时保存你的对象,发送一份引用的副本,你可以使用 clone 方法发送克隆的对象。

public Something getSomething()
{
    return something.clone();
}

这将返回对象浅拷贝,如果你想让深度克隆覆盖 clone() 方法希望这会有所帮助..

于 2019-02-20T13:40:03.753 回答