0

get setモデルを使用する:

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;
    }
}

しかし、私はクラスの外にreadOnly機能を備えた「何か」の変数が欲しいです(しかし、自分のクラスで書き換え可能です)。最適化されたアクセスのためにこれを行う方法のアイデア。(これはAndroidで使用されると思いますが、純粋なJavaのみのフレームワーク(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 に答える