访问在另一个内创建的对象

时间:2015-01-20 20:04:36

标签: java design-patterns scope singleton instance

我觉得我的问题很简单,但我不知道谷歌的用途。

我有一个run.java,基本上就是这个

public class run {
    //stuff
    public static void main(String[] args) {
        //stuff     
        Solver solver = new Solver(body,seeds);
        solver.solve();
        LogTool.print("OUTPUT field of CLASS CREATED IN solver -- " + IDONTKNOWHOW,"notification");
    }
}
===========
public class Solver {
    //stuff
    public void solve() {
        //stuff
        GlobalState GLowestState = new GlobalState(this.Cur_state);
    }
}

那么,我如何从run.java中访问GLowestState?

使用Singleton实现GLowestState会有所不同吗? 我希望不是。
我无法尝试任何东西,因为我的IDE给了我GLowestState.IDONTKNOWHOW的错误。

==============

使用更多代码进行更新:

public class run {
public static void main(String[] args) {

        Voxel [][][] body = new Voxel[Config.xDIM][Config.yDIM][Config.zDIM];
         //stuff

        Solver solver = new Solver(body,seeds);        

        LogTool.print("Initialized Solver Object!","notification");
        LogTool.print("Beginning Annealing...","notification");
        looper.solveSA();
        GlobalState GLS = looper.getGLowestState();  <--- NPE here
        LogTool.print("GLC: " + looper.getGlobal_lowest_cost()+ " CURC: " + looper.getCur_cost(),"notification");
//        LogTool.print("GLS external: " + GLS,"notification");
        LogTool.print("SolveSA: Global Current Best Solution : " + looper.getGlobal_Lowest_state_string(),"notification");

=========
public class Looper {
    public static Voxel [][][] body; //Thobi hat das als ganz einfache Variable in seiner Loesermethode...nicht so OOP
    public static Seed[] seeds = new Seed[Config.SAnumberOfSeeds];
    public double[] Cur_state = new double[Config.SAnumberOfSeeds];
    public double[] New_state = new double[Config.SAnumberOfSeeds]; // Do I even need this ?
    public double[] Global_Lowest_state = new double[Config.SAnumberOfSeeds]; // Do I even need this ?
    GlobalState GLowestState;

    public Looper(Voxel [][][] body, Seed[] seeds) {
        this.temperature = Config.StartTemp;
        this.body = body;
        this.seeds = seeds;
                this.Cur_cost = Cur_cost;
                this.New_cost = New_cost;
                this.temperature = temperature;
                this.Cur_state = Cur_state;
                this.New_state = New_state;
                this.Global_lowest_cost = Double.MAX_VALUE;
                this.Global_Lowest_state = Global_Lowest_state;
    }

    public GlobalState getGLowestState() {
        return GLowestState;
    }



        for (int ab = 0; ab < Config.NumberOfMetropolisResets; ab++) {
            LogTool.print("==================== START CALC FOR OUTER ROUND " + ab + "=========================","notification");

            if (Config.SAverboselvl==1) {
                LogTool.print("SolveSA: Cur_State Read before Metropolis : A)" + Cur_state[0] + " B) " + Cur_state[1] + " C) " + Cur_state[2],"notification");
                LogTool.print("Debug: GLS get 1: " + this.getGlobal_Lowest_state_string(),"notification");
            }

            if (ab==0){
                this.initState();

                if (Config.SAverboselvl==1) {
                    LogTool.print("SolveSA: Cur_state after Initstate : A)" + Cur_state[0] + " B) " + Cur_state[1] + " C) " + Cur_state[2],"notification");
                }
            }

            setCur_cost(cost());

            /* [Newstate] with random dwelltimes */
            newState(); 
            if (Config.SAverboselvl==1) {
                LogTool.print("SolveSA: New State before Metropolis: A)" + New_state[0] + " B) " + New_state[1] + " C) " + New_state[2],"notification");
            }

            setNew_cost(cost());

            if (Config.SAverboselvl==1) {
                LogTool.print("SolveSA: New Cost : " + New_cost,"notification");
            }

            double random_double = RandGenerator.randDouble(0.01, 0.99);

            /**
                * MetropolisLoop
                * @param Config.NumberOfMetropolisRounds
             */

            for(int x=0;x<Config.NumberOfMetropolisRounds;x++) {   
    //            break;
    //            LogTool.print("SolveSA Iteration " + x + " Curcost " + Cur_cost + " Newcost " + New_cost,"notification");
               if ((Cur_cost - New_cost)>0) { // ? die Kosten

                   if (Config.SAverboselvl>1) {
                       LogTool.print("Fall 1","notification");
                   }

                   if (Config.SAdebug) {                      
                          LogTool.print("SolveSA: Metropolis NewCost : " + this.getNew_cost(),"notification");
                          LogTool.print("SolveSA: Metropolis CurCost : " + this.getCur_cost(),"notification");
                          LogTool.print("SolveSA Cost delta " + (Cur_cost - New_cost) + " ","notification");
                   }
                          Cur_state = New_state;
                          Cur_cost = New_cost;

                    } else if (Math.exp(-(Cur_cost - New_cost)/temperature)> random_double) {

                        Cur_state = New_state;
                        Cur_cost = New_cost;

                        if (Config.SAdebug) {
                            LogTool.print("SolveSA: NewCost : " + this.getNew_cost(),"notification");
                            LogTool.print("SolveSA: CurCost : " + this.getCur_cost(),"notification");
                        }

                        if (Config.SAverboselvl>1) {
                            LogTool.print("Fall 2: Zufallsgenerierter Zustand traegt hoehere Kosten als vorhergehender Zustand. Iteration: " + x,"notification");
                        }
                    }

               temperature = temperature-1;
               if (temperature==0)  {
                   break;
               }

               random_double = RandGenerator.randDouble(0.01, 0.99);
               newState();
               setNew_cost(cost());
            }

            if (ab==9) {
                double diff=0;
            }

//This is where the trouble happens - GlobalLoewst cost is set correctly and kept throughout the loops, GLowestState is always the last value of Cur_State (the most recent completed iteration. If smoothly running, that would be iteration 9 and inner iteration 99) @stackexchange

            if (Cur_cost<Global_lowest_cost) {
                this.setGlobal_lowest_cost(Cur_cost);
                GlobalState GLowestState = new GlobalState(this.Cur_state);
                LogTool.print("GLS DEDICATED OBJECT STATE OUTPUT  -- " + GLowestState.getGlobal_Lowest_state_string(),"notification");
                this.setGlobal_Lowest_state(GLowestState.getDwelltimes());
                LogTool.print("READ FROM OBJECT OUTPUT  -- " + this.getGlobal_Lowest_state_string(),"notification");
//                LogTool.print("DEBUG: CurCost direct : " + this.getCur_cost(),"notification");        
//                LogTool.print("Debug: Cur<global CurState get : " + this.getCur_state_string(),"notification");
//                LogTool.print("Debug: Cur<global GLS get : " + this.getGlobal_Lowest_state_string(),"notification");
//                this.setGlobal_Lowest_state(this.getCur_state(Cur_state));
//                LogTool.print("Debug: Cur<global GLS get after set : " + this.getGlobal_Lowest_state_string(),"notification");        
            }
            LogTool.print("SolveSA: Iteration : " + ab,"notification");
            LogTool.print("SolveSA: Last Calculated New State/Possible state inner loop 99 : " + this.getNew_state_string(),"notification");
//            LogTool.print("SolveSA: Best Solution : " + this.getCur_state_string(),"notification");
            LogTool.print("SolveSA: GLS after: " + this.getGlobal_Lowest_state_string(),"notification");
            LogTool.print("SolveSA: NewCost : " + this.getNew_cost(),"notification");
            LogTool.print("SolveSA: CurCost : " + this.getCur_cost(),"notification");        
        }
    }

=================

public final class GlobalState implements Comparable<Object>{
    private double[] dwelltimes;
    private static GlobalState instance = null;

    protected GlobalState(){
        // Exists only to defeat instantiation
    }

    public static GlobalState getInstance(){
        if (instance==null){
            instance = new GlobalState();
        }
        return instance;
    }

    public GlobalState(double[] dwelltimes) {
        this.dwelltimes = dwelltimes;
    }

    @Override
    public int compareTo(Object o) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public double[] getDwelltimes() {
        return dwelltimes;
    }

    public String getGlobal_Lowest_state_string() {
        String Global_Lowest_state_string = new String();
        for (int cc = 0; cc < Config.SAnumberOfSeeds; cc++) {
            Global_Lowest_state_string = Global_Lowest_state_string.concat(" " + cc + ") " + dwelltimes[cc]);
            }
        return Global_Lowest_state_string;
    }

    public void setDwelltimes(double[] dwelltimes_x) {
        this.dwelltimes = dwelltimes_x;
    }

}

6 个答案:

答案 0 :(得分:0)

如果GLowestStateSingleton,那么你真的无法在其上调用new - 假设它是一个实施良好的单身人士。

如果实施得很好,那么你可以这样称呼它:

GLowestState.getInstance();

另一个例子:

 GLowestState.getInstance().foo();

答案 1 :(得分:0)

可以这样做:

public class Solver {
    private GlobalState GLowestState;

    public void solve() {
        GLowestState = new GlobalState(this.Cur_state);
    }

    public GlobalState  getGLowestState() {
        return GLowestState;
    }
}

答案 2 :(得分:0)

如果您希望Solver成为单身人士,则需要私有构造函数和newInstance方法。 创建一个字段gloweststate并使用getter访问它

public class run {
    //stuff
    public static void main(String[] args) {
        //stuff
        Solver solver = Solver.getInstance().solve(body,seeds);
        LogTool.print("OUTPUT field of CLASS CREATED IN solver -- " + solver.getGLowestState(),"notification");
    }
}
===========
public class Solver {

    private GlobalState gLowestState;
    private static Solver singeltonSolver;

    private Solver() {

    }

    public synchronized static Solver getInstance(){
        if(singeltonSolver== null)
            singeltonSolver = new Solver();
         return singeltonSolver;
    }

    public void solve( SOmeType body,SOmeType seeds) {
        //stuff
        GlobalState GLowestState = new GlobalState(this.Cur_state);
    }

    public GlobalState getGLowestState() {
        return gLowestState;
    }
}

答案 3 :(得分:0)

您需要为班级内的对象实施getter,并将变量设为instance variable,而不是local variable。对于您的代码,一个例子是:

public class Solver {
    // stuff
    GlobalState GLowestState;

    public void solve() {
        // stuff
        GLowestState = new GlobalState(this.Cur_state);
    }
    public GlobalState getGLowestState(){
        return GLowestState;
    }
}

注意GLowestState现在如何属于类的实例,而不是方法solve()中的局部变量。你现在可以打电话了

Solver solver = new Solver(body,seeds);
solver.solve();
GlobalState GS = solver.getGLowestState();

变量GS将继续GlobalState对象的特定实例的Solver变量。

答案 4 :(得分:0)

我要做的是让GlobalState持有单身人士。

public enum GlobalState {
    INSTANCE;

    public String getValue() { ... }
}

然而,Solver保持其状态并且不会混淆全球状态会更好。

public class Solver {
    final String field;
    //stuff
    public Solver(int body, int seeds) {
        //solve stuff here
        this.field = "value";
    }
}

public class Run {
    //stuff
    public static void main(String[] args) {
        //stuff
        Solver solver = new Solver(body,seeds);
        LogTool.print("OUTPUT field of " + solver.field);
   }
}

答案 5 :(得分:0)

它可以通过多种方式实现:

1-如果GlowestStatesolve()特别相关,则返回并使用返回的对象。

 public GlobalState solve() {
    GlobalState globalState = new GlobalState(this.Cur_state);
    return globalState;
}

现在您可以按以下方式访问它:

Solver solver = new Solver(body,seeds);
GlobalState globalState = solver.solve();

2-制作GlowestState个实例并将其公开。

public GlobalState glowestState;
public void solve() {
    GLowestState = new GlobalState(this.Cur_state);
}

然后你可以通过调用solver.glowestState

来获得它

3-使用getter获取GLowestState

private GlobalState glowestState;
public void solve() {
    glowestState = new globalState(this.Cur_state);
}

public getGlowestState() {
    return GLowestState;
}

现在您可以致电getGlowestState()

来获取它