开发者

implicitly pass parameters to class

I am writing a class in Android that requires certain parameters from the class that calls its functions.

For Example my class is called "DoStuff"

DoStuff has 3 functions:

public static doThis(canvas, tick, toggle, something);
public static doThat(canvas, tick, toggle, something, something);
public static doTheOther(canvas, tick, toggle, something, something, something);

Is there a way for me to have canvas, tick and toggle implicetly passed to the "DoStuff" when I call on it's functions from somewhere else (that somewhere 开发者_高级运维is unknown to DoStuff).


It would be a terrible idea, to design it that way. Why don't make a proper class out of it and instantiate it?

Static functions shall only be used, when the function itself doesn't depend on some class variables. So, to have it cleanly solved and not to risk some kind of memory leaks/collisions between calls of it from different parts of your App, you basically have to either keep it the way you already have it and pass every parameter necessary to the function, or make a class (with non-static functions), instantiate it with the values you want and then only pass the something values to the functions.

Other than that, there is no clean solution. I'd advise you against storing the values into public static, because this could either lead that some stuff can't be released/cleaned up by the GC because the Canvas is still assigned in the static field or that one app may set it's values, then another do too and overwrites the first apps/acitvities settings and when the first app again calls the functions it gets unpredictable results.

Just a question as a side-note: Why do you want to keep it static, if that three variables are so often used/passed? non-static would make just more sense OOP wise


The best you could do is define them as global variables inside the DoStuff class and set them only when you need to and have all functions get the values from these global vars. That way you can change them only when you have to, via a diferent method.

That way, you can set them once and use them various time, but you have to make sure these values are not null at runtime, it takes some tinkering to have the values always be present depending on how you want you class to behave.


Just have three different constructors to pass in the arguments and pick the right one before you instantiate it, then call the method you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜