Evening all, and thanks in advance for your wisdom.
Bear with me if I show ignorance, but here is how my project is currently built:
-TitleScreen: first class which appears. Extends Sprite.
-Startup: class I use to call other classes. Extends Sprite.
-GameScreen: the "game engine" class. Extends AssetsHandler.
-AssetsHandler: where most of the methods to manipulate the assets are. Extends GrfAssetsStore.
-GrfAssetsStore: where all graphical assets are stored. Extends Sprite.
-Level01: first level class. Extends GameScreen.
Now: when I start everything up, all is hunky dory. So, let's say I finish level 1, and I want to restart, or go to title screen: again no problems, BUT I re-instantiate the GameScreen class -and in turn AssetsHandler, and in turn GrfAssetsStore. Mind you I have not set up any EventListeners that call them back up -indeed, I tried to make sure that once started, they would be left undisturbed- but in my ignorance I've now realised that restarting Level01 is in turn re-extending the other classes.
Understandably this is greatly undesirable, but so far I cannot overcome it. I tried just instantiating the super classes within Level01 -same issue.
The aim pretty much is having GameScreen, AssetsHandler and GrfAssetsStore running under the bonnet, so to speak, while new levels are begun and ended, but without in turn restarting the superclasses, just getting methods/variables etc. from them.
So: how do I overcome this? And no, I am not greatly experienced in AS3, so I appreciate if this is obvious to actual experts, hence why I am here.
If I need to word anything better please do not hesitate in saying such.
EDIT: the issue now I believe isn't the extending, but me not de-referencing correctly the variables etc., thanks Josh for helping me realise such. As you mentioned, it makes little sense to deny one of the major aspects of OOP: as such I should defo not consider applying that incorrect logic.
I'll attempt to better GC (and force GC if necessary) until I have removed correctly all references. If this doesn't work though...I'll post another, more detailed question.
You could set it up as a Singleton.
Basic structure:
public class ClassName {
private static var _instance:ClassName;
public function ClassName() {
// run normal constructor code here
}
public static function get instance():ClassName {
if ( !_instance ) {
_instance = new ClassName();
}
return _instance;
}
}
So instead of you ever calling new ClassName() in your code, you just call ClassName.instance to access the single instance of that class. That will return the same single instance every single time, and create it if it has not already been created. This will ensure there is never more than a single instance of the code at any given time (assuming you never call new ClassName() of course)
Note that this is not a design pattern that should be used often, if at all. It goes against basic OOP principles and is a highly debated design pattern for that reason. I think this works in this case because you do not want more than one instance of your game running at any given time, but in most cases you should write your code to avoid this pattern.
http://en.wikipedia.org/wiki/Singleton_pattern
Related
I want to create a controller based JavaFX GUI consisting of multiple controllers.
The task I can't accomplish is to pass parameters from one Scene to another AND back.
Or in other words:
The MainController loads SubController's fxml, passes an object to SubController, switches the scene. There shall not be two open windows.
After it's work is done, the SubController shall then switch the scene back to the MainController and pass some object back.
This is where I fail.
This question is very similar to this one but still unanswered. Passing Parameters JavaFX FXML
It was also mentioned in the comments:
"This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
– Xlint Xms Sep 18 '17 at 23:15"
I used the first approach in the top answer of that thread.
Does anyone have a clue how to achieve this without external libs?
There are numerous ways to do this.
Here is one solution, which passes a Consumer to another controller. The other controller can invoke the consumer to accept the result once it has completed its work. The sample is based on the example code from an answer to the question that you linked.
public Stage showCustomerDialog(Customer customer) {
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"customerDialog.fxml"
)
);
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(
new Scene(
(Pane) loader.load()
)
);
Consumer<CustomerInteractionResult> onComplete = result -> {
// update main screen based upon result.
};
CustomerDialogController controller =
loader.<CustomerDialogController>getController();
controller.initData(customer, onComplete);
stage.show();
return stage;
}
...
class CustomerDialogController() {
#FXML private Label customerName;
private Consumer<CustomerInteractionResult> onComplete
void initialize() {}
void initData(Customer customer, Consumer<CustomerInteractionResult> onComplete) {
customerName.setText(customer.getName());
this.onComplete = onComplete;
}
#FXML
void onSomeInteractionLikeCloseDialog(ActionEvent event) {
onComplete.accept(new CustomerInteractionResult(someDataGatheredByDialog));
}
}
Another way to do this is to add a result property to the controller of the dialog screen and interested invokers could listen to or retrieve the result property. A result property is how the in-built JavaFX dialogs work, so you would be essentially imitating some of that functionality.
If you have a lot of this passing back and forth stuff going on, a shared dependency injection model based on something like Gluon Ignite, might assist you.
I've used AfterBurner.fx for dependency injection, which is very slick and powerful as long as you follow the conventions. It's not necessarily an external lib if you just copy the 3 classes into your structure. Although you do need the javax Inject jar, so I guess it is an eternal reference.
Alternately, if you have a central "screen" from which most of your application branches out you could use property binding probably within a singleton pattern. There are some good articles on using singleton in JavaFX, like this one. I did that for a small application that works really great, but defining all of those bindings can get out of hand if there are a lot of properties.
To pass data back, the best approach is probably to fire custom Events, which the parent controller subscribes to with Node::addEventHandler. See How to emit and handle custom events? for context.
In complex cases when the two controllers have no reference to each other, a Event Bus as #jewelsea mentioned is the superior option.
For overall architecture, this Reddit comment provides some good detail: https://www.reddit.com/r/java/comments/7c4vhv/are_there_any_canonical_javafx_design_patterns/dpnsedh/
EDIT: I figured this problem out on my own, and have included the answer below.
I have a variable in my main timeline called characterDismissed which is a Boolean. I also have a series of nested MovieClips (MovieClips within MovieClips) which look something like: Stage > Container > List > Buttons.
In the Buttons MovieObject at the bottom of the nest I'm trying to output characterDismissed's value just to see if it can see or modify it:
trace("characterDismissed is: " + characterDismissed);
This obviously doesn't work, and I understand why it doesn't work (because characterDismissed is not a variable in the Buttons ActionScript, but rather in the main timeline's ActionScript, so it has no concept of the characterDismissed variable yet.)
How would I go about making this variable accessible to the Buttons MovieClip in AS3? I've tried root.characterDismissed, parent.characterDismissed, this.parent.characterDismissed, even parent.parent.parent.characterDismissed, etc. These always give me some flavor of this error, however:
1119: Access of possibly undefined property characterDismissed through a reference with static type flash.display:DisplayObjectContainer.
I feel like I've been reading suggestions for handling this for days, but nothing is working, and with my understanding of AS3 being limited already, I don't have a proper grasp on the vocabulary to better research it past what I've already searched, or make sense of what typically ends up being a vague response on other forums, or for similar, but not-quite-right questions/answers.
I ended up figuring out the answer on my own, here's what I came up with:
I made a new ActionScript 3.0 Class file and named it GlobalVars (though, you can name it whatever you like.) and saved it into my project directory alongside my main .FLA file. In GlobalVars I made a test variable named testVar, set it to public, and then static.
My understanding for this is that public means anything can modify it, and static means that this variable will be the same value throughout your entire program. That looks like this:
public static var testVar:Number = 1234;
Then in both my Main project AS3, and the nested object's AS3 I added:
import GlobalVars;
This adds the class I made, and any functions or variables I configured within GlobalVariables to my Main AS3 script on the timeline.
Now, I have can access or change my variables in those AS3 scripts by simply prefixing the variable with the class name, like so:
GlobalVars.testVar += 20; // Add 20 to testVar.
Now, as long as I import GlobalVars into my script, I can access, and modify these variables from anywhere.
Hope this helps anybody else out there who found themselves lacking the vocabulary to properly articulate a search on this subject. I have attempted to include as many keywords in my explanation as possible to help people with similar search queries.
I appreciate Robotlegs very much, but recently a GC problem came to me. I failed to dispose context object by just set the reference null.With the help of FB profile tool, I find that context object appears to be a "GC Root".
To figure it out, I wirte a simple class, which creates a context obj and leave it unreachable.Here is the detail of this class:
public class MemoryLeak extends Sprite{
public function MemoryLeak()
{
makeAndDrop();
}
public function makeAndDrop():void{
var _context = new Context(this);
_context = null;
}
}
When I ran this class, I hoped it be disposed by GC, but it didn't work(most times, not everytime). And the profile tool show me this instance is a GCRoot. I read some articles about GC, but few of them mention GCRoot itself. Could anybody tell me why and thank you so much!
PS: I tried to call System.gc() twice after makeAndDrop() but it didn't work. In fact, I'm more interested in the "is GCRoot" issue(implied by the fb profile), it may help more if you tell me about it.
I think the Context will probably listen to this so that it can perform dependency injection on any added children or create mediators for them. One would hope that the listener would not be attached until you talk to the mediatorMap or the viewMap, but I think it is likely that the RL authors would not consider a use case where you'd want a Context on a View for a time period shorter than the View's actual lifespan.
I currently pass a reference to my model through the constructor to any class that needs it in my simple mvc pattern, this can get annoying at times when it starts to go deeper.
How do Classes such as LoadMax allow you from anywhere to simple import the class, and do something like addChild(LoaderMax.getContent("bg"));? Replicating this should surely be a good way to have my model work, without the complexity of big frameworks?
Statics are your friend
As previous answers have noted, TweenLite/Max etc. makes heavy use of static members to get work done. This is exactly like the Math class, for example, and can be a very convenient design pattern. You have global access to the class, and that can definitely alleviate the issue of getting access to variables through deeply nested classes.
Statics are the enemy
Statics, however, bring certain problems to the table. Most importantly, they tend to reduce flexibility and modularity of classes through the often unnecessary addition of tightly coupled relationships. It's a bit like pouring concrete over your application. It does work, but changing behavior becomes difficult as project features change.
Static members != instance members
Note, very clearly, that a static member "belongs" to the class itself, and not an instance of that class. Static members have no access to instance members. This causes troubles when you want to mix these members up in logic. You tend to have to make everything static (the so-called "static-cling" effect). Static patterns are often argued to be argued to be "anti" object-oriented, for precisely this reason. Once you build a structure on a static pattern you tend to lose many of the principles that makes OOD powerful.
In small does, they're pretty nice
That all being said - TweenLite is a great example of a static pattern that is totally appropriate - its a utility package, one that logic is not dependent on. And that should probably be how you leverage statics, too.
To reduce reliance on statics, or even global vars, it does often mean writing more code, but the flexibility in app structure gained is often quite worth it. #Marty_Wallace has a pretty good solution imo.
Demeter and the Paperboy
Finally, I'll just mention the Law of Demeter, or the Principle of Least Knowledge, and the related Paperboy and the Wallet example, which is often pointed to in discussions of statics:
Each unit should have only limited knowledge about other units: only
units "closely" related to the current
unit.
Each unit should only talk to its friends; don't talk to strangers.
Only talk to your immediate friends.
Hopefully that sheds a little bit of light on a fairly complicated and not-often obvious issue.
This is done using the static namespace, however I discourage the use of this.
package
{
public class Main
{
public static function sayHell():void
{
trace("hello!");
}
}
}
You can now call sayHello() like this from anywhere in the application (assuming you've imported the class).
Main.sayHello();
Another thing you can do (to make the entire class accessible from within the application) is create a static property that refers to the class itself:
package
{
public class Something
{
public static var instance:Something;
public function Something()
{
instance = this;
}
public function someFunction():void
{
trace('hello!');
}
}
}
Which you can now use like so:
Something.instance.someFunction();
The only thing to note here is that you need to create an instance of Something for this to work to call the constructor and define instance.
What I would do
Create a base class for all objects in your application
Create a manager class that takes care of these objects
Create a setter within your base class to define the manager
Here's an example:
Base
package
{
public class Base extends Object
{
private var _manager:Manager;
public function set manager(m:Manager):void
{
_manager = m;
init();
}
protected function init():void
{
manager.someFunction();
}
public function get manager():Manager{ return _manager; }
}
}
Manager
package
{
public class Manager extends Object
{
public function someFunction():void
{
trace('hello!');
}
}
}
Now anything that extends Base will have access to anything held in Manager via the manager getter property. All you need to do is make sure you define the manager, which is easily achieved from within anything that extends Base like so:
var something:SomeExtendingClass = new SomeExtendingClass();
something.manager = manager;
The example you gave is just a static method, but to answer your question about a global instance of a class:
package myPackage
{
public var globalVariable:MyClass = new MyClass();
}
You can access it with:
import myPackage.globalVariable;
trace(globalVariable);
I think you have to rethink in which way you want to name your classes.
You can instantiate whatever class you want, at run-time, but to access a instance by name, you have to make changes in your structure. For example, the getContent() function you mentioned in LoaderMax, all it does is to search in an array for the given loader that matchs the name, among other things. You can read the name variable comment for a description.
A name that you use to identify the loader instance. This name can be fed to the getLoader() or getContent() methods or traced at any time. Each loader's name should be unique. If you don't define one, a unique name will be created automatically, like "loader21".
So in this system, you have to name every single member (loaders in this case) if you want to be able to search them. Because if I call getClassInstance("myinstance"), what is "myinstance" representing? Where should I name it?
That said, if you want to do it for DisplayObjects only, you can use getChildByName. But again, you have to name every DisplayObject (just set the name variable).
Hope this helps.
This question is language agnostic but I am a C# guy so I use the term POCO to mean an object that only preforms data storage, usually using getter and setter fields.
I just reworked my Domain Model to be super-duper POCO and am left with a couple of concerns regarding how to ensure that the property values make sense witin the domain.
For example, the EndDate of a Service should not exceed the EndDate of the Contract that Service is under. However, it seems like a violation of SOLID to put the check into the Service.EndDate setter, not to mention that as the number of validations that need to be done grows my POCO classes will become cluttered.
I have some solutions (will post in answers), but they have their disadvantages and am wondering what are some favorite approaches to solving this dilemma?
I think you're starting off with a bad assumption, ie, that you should have objects that do nothing but store data, and have no methods but accessors. The whole point of having objects is to encapsulate data and behaviors. If you have a thing that's just, basically, a struct, what behaviors are you encapsulating?
I always hear people argument for a "Validate" or "IsValid" method.
Personally I think this may work, but with most DDD projects you usually end up
with multiple validations that are allowable depending on the specific state of the object.
So I prefer "IsValidForNewContract", "IsValidForTermination" or similar, because I believe most projects end up with multiple such validators/states per class. That also means I get no interface, but I can write aggregated validators that read very well reflect the business conditions I am asserting.
I really do believe the generic solutions in this case very often take focus away from what's important - what the code is doing - for a very minor gain in technical elegance (the interface, delegate or whatever). Just vote me down for it ;)
A colleague of mine came up with an idea that worked out pretty well. We never came up with a great name for it but we called it Inspector/Judge.
The Inspector would look at an object and tell you all of the rules it violated. The Judge would decide what to do about it. This separation let us do a couple of things. It let us put all the rules in one place (Inspector) but we could have multiple Judges and choose the Judge by the context.
One example of the use of multiple Judges revolves around the rule that said a Customer must have an Address. This was a standard three tier app. In the UI tier the Judge would produce something that the UI could use to indicate the fields that had to be filled in. The UI Judge did not throw exceptions. In the service layer there was another Judge. If it found a Customer without an Address during Save it would throw an exception. At that point you really have to stop things from proceeding.
We also had Judges that were more strict as the state of the objects changed. It was an insurance application and during the Quoting process a Policy was allowed to be saved in an incomplete state. But once that Policy was ready to be made Active a lot of things had to be set. So the Quoting Judge on the service side was not as strict as the Activation Judge. Yet the rules used in the Inspector were still the same so you could still tell what wasn't complete even if you decided not to do anything about it.
One solution is to have each object's DataAccessObject take a list of Validators. When Save is called it preforms a check against each validator:
public class ServiceEndDateValidator : IValidator<Service> {
public void Check(Service s) {
if(s.EndDate > s.Contract.EndDate)
throw new InvalidOperationException();
}
}
public class ServiceDao : IDao<Service> {
IValidator<Service> _validators;
public ServiceDao(IEnumerable<IValidator<Service>> validators) {_validators = validators;}
public void Save(Service s) {
foreach(var v in _validators)
v.Check(service);
// Go on to save
}
}
The benefit, is very clear SoC, the disadvantage is that we don't get the check until Save() is called.
In the past I have usually delegated validation to a service unto its own, such as a ValidationService. This in principle still ad hears to the philosophy of DDD.
Internally this would contain a collection of Validators and a very simple set of public methods such as Validate() which could return a collection of error object.
Very simply, something like this in C#
public class ValidationService<T>
{
private IList<IValidator> _validators;
public IList<Error> Validate(T objectToValidate)
{
foreach(IValidator validator in _validators)
{
yield return validator.Validate(objectToValidate);
}
}
}
Validators could either be added within a default constructor or injected via some other class such as a ValidationServiceFactory.
I think that would probably be the best place for the logic, actually, but that's just me. You could have some kind of IsValid method that checks all of the conditions too and returns true/false, maybe some kind of ErrorMessages collection but that's an iffy topic since the error messages aren't really a part of the Domain Model. I'm a little biased as I've done some work with RoR and that's essentially what its models do.
Another possibility is to have each of my classes implement
public interface Validatable<T> {
public event Action<T> RequiresValidation;
}
And have each setter for each class raise the event before setting (maybe I could achieve this via attributes).
The advantage is real-time validation checking. But messier code and it is unclear who should be doing the attaching.
Here's another possibility. Validation is done through a proxy or decorator on the Domain object:
public class ServiceValidationProxy : Service {
public override DateTime EndDate {
get {return EndDate;}
set {
if(value > Contract.EndDate)
throw new InvalidOperationexception();
base.EndDate = value;
}
}
}
Advantage: Instant validation. Can easily be configured via an IoC.
Disadvantage: If a proxy, validated properties must be virtual, if a decorator all domain models must be interface-based. The validation classes will end up a bit heavyweight - proxys have to inherit the class and decorators have to implement all the methods. Naming and organization might get confusing.