I have three classes interacting in an interesting way. One is a model class, and it has to be accessed by both of the other classes, so a single instance of it is kept as a member of each. Both of these classes interact with the model in different ways.
There are a couple of instances where the model object has to be completely thrown away and replaced with a new instance, and this complicates things. And these occasions arise in both of the viewing/controlling classes. So, either one of those classes has to be able to send a signal to the other saying "We need to coordinate and facilitate the replacement of our Model object with a new Model object." Right now I have code in class B to tell class A to construct a new Model and send it back, but now I need to handle the opposite situation, where the event arises in class A, and unfortunately class A does not have a reference to class B and probably shouldn't.
What's a good way to handle this?
Update: Sorry, folks, this can't be a singleton. Singletons are when you need to guarantee there's only one of something. That has nothing to do with any of the requirements I expressed above. This class is not a singleton and shouldn't be.
Update: Up till now, there has actually only been one instance of this Model class, but I had a vague suspicion I needed to allow for more, and I didn't want to limit myself by using the Singleton design pattern when that actually addresses different concerns from what I have. Turns out I was right: yesterday I received a new requirement and now I need support an arbitrary number of these. :) Don't limit yourself when you don't have to, and don't misuse design patterns for situations where they were not intended!
You'll want an intermediary model layer, a model "holder" object that each of the two classes reference. The ModelHolder holds a reference to the model.
This ModelHolder should also support listeners, so when its model is thrown out, it can notify any listeners that the model has changed.
Ok, if you need to change the model (but not force) you can make a listener interface, and make both objects A and B implement it:
public interface ModelListener {
public void modelChanged(Model newModel);
}
and at the proper time you can notify the listeners of the new model change. You can also have a list that holds all the registered listeners.
List<ModelListener> modelListeners = new ArrayList<ModelListener>();
public void setNewModel(Model m) {
for (ModelListener aListener : m.modelListeners)
aListener.modelChanged(m);
}
As always there are tradeoffs between simplicity and robustness. You might want to experiment with the levels you need for your own case.
I encounter this design issue often in GUI projects (Swing, GWT). What I usually do is create a higher-level "State" model, which holds an instance of the object that is shared between 2 or more classes. State then has a ModelListener interface, which the other classes can implement to get notification of changes to the underlying model. State.setFoo() then fires ModelChanged events to the listeners, which respond accordingly.
Related
Disclaimer: I’m new to programming in Java and working with “extreme” OOP in general, so the answer to this might be really simple.
I’m creating a user interface in Vaadin, a Web application framework that supplies lots of useful components for me. Often, I’m not entirely happy with the default settings for these components.
For example, if I want every TextField component to fire value change events immediately when the field loses focus. There are similar settings for UploadField, TextArea, ComboBox etc. that I want to set on every instance of those classes.
Currently, what I have looks like this:
public class ConfiguredComponents {
public static TextField createConfiguredTextField(String caption) {
TextField field = new TextField(caption);
field.setImmediate(true);
field.setSomeOtherOptions();
...
return field;
}
public static UploadField createConfiguredUploadField(...) {
...
}
// etc.
}
This doesn’t feel like a class at all! It’s just a collection of static methods, which I’ve been told to avoid. Plus, I would like to place the logic for each component in a separate file. The configuration gets quite involved sometimes, and it just makes more sense that way: these are all very tiny self-contained bits of logic.
Here are the solutions I’ve considered:
Keep it simple: I could get rid of ConfiguredComponents, and just make one big package containing small factory classes. For example, myproject.ui.components.TextFieldFactory knows how to create a configured TextField and nothing more.
Pros:
The ugly ConfiguredComponents class is gone.
All of the logic is in separate files.
Cons:
There’s no single interface to the creation of my configured components; the only thing keeping them together is the fact that they’re in the same directory. Basically, I have to expose a lot of tiny classes, and there’s no single class or object managing them. (This intuitively feels like a pretty bad thing, but I don’t know if it really is.)
There’s also no way to override or extend static methods, so “faking” UI stuff for testing gets harder.
The Abstract Factory pattern: I make ConfiguredComponents into an AbstractComponentFactory that manages a lot of smaller factories.
Pros:
All of the logic is in separate files.
The logic that actually configures my components is fully behind-the-scenes.
Cons:
I would need an instance of AbstractComponentFactory every time I want to create a component anywhere in the code for my views. This means either keeping a singleton object, which has a lot of downsides, or creating a new AbstractComponentFactory() every time.
I have to write new code in two or three places, instead of just one, if I wish to add new components to my little “library”.
Some other design pattern I don't know about: I’ve read a bit about Builder, and Facade, which feel like they might apply here, but I don’t understand them very well.
How would you approach this design decision?
If your components can be inherited, then go ahead; for each component that you want to alter default settings, create a new derived class and config settings in constructors. Otherwise,
Abstract factory pattern is a good choice. I think you are misunderstanding about this pattern. AbstractComponentFactory is just an interface, it does not manage anything. This interface looks like this:
interface AbstractComponentFactory {
public TextField createTextFiled(...);
public UploadField createUploadFiled(...);
...
}
In your situation, I think you need only one implementation for this factory:
class MaurisComponentFactory implements AbstractComponentFactory {
public TextField createTextFiled(...) {
new ... config ... return;
}
public UploadField createUploadFiled(...) {
new ... config ... return;
}
...
}
As you said, we should neither use Singleton nor create new MaurisComponentFactory everytime. Instead, we should create only one instance in the main() method, and then try to inject this instance to every place that need to create components.
One possible approach i can think think is to use AbrstractFactory with Service Locator or Registry patterns
Since you have myriad objects that does not have complicated instantiation process (if so resort to build pattern), you create objects with Abstract Factory and register them in registry. And resolve them as needed where ever you are.
or you may resort simple IOC container where your entire application is wrapped around
We have an application that is composed of a number of independent components and sub-systems. We are looking at implementing a simple event logging mechanism where these components & sub-systems can log some events of interest. Events could be something like
New account created
Flight arrived
Weekly report dispatched to management etc.
As you can see, the event types are heterogeneous in nature and the attributes that needs to be logged differs based on the event types. New account created event, for example, will also log the account-id, the name of the user who created the new account etc. Whereas, the flight arrived event will be logging the flight number, arrived at, arrived from etc.
I'm wondering what is the good way of modelling the event types and the attributes.
One option is to do it object oriented way - to have an AbstractEvent that will have some common attributes (timestamp, message etc) and then create a full hierarchy of classes underneath. The flight events, for example, can look like
abstract class AbstractEvent;
abstract class FlightEvent extends AbstractEvent;
class FlightArrivedEvent extends FlightEvent;
class FlightCancelledEvent extends FlightEvent;
The problem I see with this approch is that we have hundreds of events which will result in class explosion. Also, whenever we add a new event (very likely), we have to create a class and distribute the new package to all the components and sub-systems.
The second option I can think of is on the other end of the spectrum. Have a simple Event class that contains the basic attributes and wrap a map inside it so that the clients can populate any data they want. The code in that case will look something like this.
class Event {
private timestamp;
private eventType;
private Map attributes;
public Event ( String eventType ) {
timestamp = System.nanoTime();
this.eventType = eventType;
attributes = new HashMap();
}
public Event add ( String key, String value ) {
attributes.put ( key, value );
return this;
}
}
//Client code.
Event e = new Event("FlightEvent:FlightArrived")
.add("FLIGHT_NUMBER", "ABC123")
.add("ARRIVED_AT", "12:34");
While this is flexible, it suffers from inconsitency. Two components can log the FLIGHT_NUMBER key in two different formats (FLIGHT_NUMBER & FLGT_NO) and I can't think of a good way to enforce some convention.
Any one have some suggestions that can provide a nice compromise between these two extreme options?
There is a Java event framework (see java.util.EventObject and the Beans framework) but the fundamental question you are asking is not connected with events. It is a design question, and it is this: do I use Java classes in my application to represent classes in my business domain?
It is clear that the different types of event are different "classes" of thing, but for maintainability reasons you are considering representing your business data in a map so that you don't have to write and distribute an actual class. If you take this to a logical extreme, you could design your whole application with no classes and just use maps and name-value pairs for everything - not just events. It would be a mess and you would be debugging it forever because you would have no type-safety whatsoever. The only way of finding what was in map would be to look up in some documentation somewhere what someone might have added to it and what type that object might be.
So, here is the thing - you would not have actually have gotten rid of your class definition.
You will have moved it into a Word document somewhere that people will have to refer to in order to understand what is in your map. The Word document will need to be maintained, verified and distributed but unlike the Java class, it won't be checked by the compiler and there is no guarantee that the programmers will interpret it correctly.
So I would say, if there is a class, put it in your code and then focus on solving the problems of distributing and versioning the Java classes instead of distributing and versioning Word documents.
I will mention versioning again as this is an issue if you might serialise the objects and restore them, so you need to think about that.
Some caveats:
If you are writing a piece of middleware software that routes events from one system to another system, it might be you don't need to know are care what the data is, and it might make sense to use a generic holder in this case. If you don't need to look at the data, you don't need a class for it.
You might get complaints from high-level designers and architects about the number of classes and the work they have to do in defining them compared with a map and name/value stuff. This is because putting classes (i.e., the real design) in Java is harder than putting them in a Word document. Easier, if you are high-level hand-waving type guy, to write something wishy-washy in Word that doesn't need to run or even compile and then give the real design work to the programmers to get working.
Can [someone] provide a nice compromise between these two extreme options?
No. There is no generic one-size-fits-all answer to this problem. You will have to find yourself a balance which fits the general design of your product. If you nail everything down, you will need thousands of classes. If you give a lot of leeway, you can get away with a few but you're paying your freedom with precision. See my blog post "Designing a Garbage Bin"
Do you have shared attributes? As in: Do you expect to define attributes of events like you define classes right now with very tight-fitting semantics?
That would mean you have a simple event and typed attributes (i.e. String value simply isn't sufficient). You need formatting and validation for attributes or ... attributes themselves need to be classes.
If this is the case, you can use my type-safe map pattern: http://blog.pdark.de/2010/05/28/type-safe-object-map/
Event type "explosion" is not a problem. In fact it is a desirable approach as it allows the components to be independent of one another. I wouldn't necessarily make all events inherit from a single superclass unless it gives you a lot of reusable code because it can cause dependencies to start proliferating.
I would put the event types in a separate project that will be a dependency of both the publisher and consumer.
What is your communication mechanism for these events between components? JMS? If so you could also consider making your messages XML and using JAXB.
I would definitely discount the map approach as it destroys any hope of polymorphism or any other oo niceties.
I am new to design patterns. I am writing a piece of code where there is one subject and multiple observers. Both subject and observers have interfaces. So say if I have 5 observers, do I need to create 5 different interfaces with their separate update methods? Or should I create just one interface and write five update methods for all observers?
Often you will need just one observer interface that all 5 observer classes can implement. What will differ will be how the observers react to the notification of change. Whether this applies to you will depend completely on your program structure and needs.
Note that observers that share a single interface can also listen for different changes in the observed, but still use the same interface. For example if you used a PropertyChangeListener as your observer interface, you could base what you listen to by checking the propertyName returned in the PropertyChangeEvent that is passed to your observer.
Note however that if what the observers are listening to are very different, then yes, they might need a unique interface. Using a Swing example, since that is what I'm most knowledgeable in, there are many different listener classes and interfaces available, including ActionListener, MouseListener, MouseMotionListener, ... all though derived from a common super interface, EventListener. Note that all pass a parameter to their listeners that is based on a common super class, the AWTEvent class.
For better more specific help, please consider giving us more specifics of your problem.
do I need to create 5 different interface with their seperate update methods? Or I should just create one interface and write five update methods for all observers?
One interface with five update methods seems much less cohesive than five different interfaces. However, you say you only have one kind of subject (which is the client to the Observers). But it depends on how cohesive is this client.
The interface segregation principle likely applies here to help you decide. If you provide more details, I could give more opinions.
IF you are using Java EE, I would suggest using topics and subscribers using JMS... It is more robust. I don't know what kind of solution you are looking for but it would be more robust if you need to persist and prevent from losing data...
Don't hesitate if you need something.
I have a question about the state pattern and how to implement it using DDD.
For what I understand of the state pattern, the pattern is used to handle the transition between different states, so its the responsibility of each state to handle what the system has to do to transit to the new state.
To do so, using polymorphism, each state can be a class of its own that extends one base class, implementing the transitions from one state to the other, following a graph that defines the possible transitions.
I've been looking for information on how to do this using DDD and, among other web sites, I found this one that uses enums.
http://nurkiewicz.blogspot.co.uk/2009/09/state-pattern-introducing-domain-driven.html
The reason for using enums is that you can persist the current state, in this case the name of the enum, to a repository, so your aggregate can be recreated later. So, following the state pattern definition, the state can receive different parameters (for example, the new value of a field) so the context (in this case the aggregate) can transit to the new state and update its fields so the state is consistent. This means, the state would be the one responsible to update the values of the aggregate.
My question is, is this the right thing to do? For what I understand, in DDD the aggregate is the one that knows about its internals and, whenever an entity inside the aggregate has to be changed, the aggregate has to expose a method which later on would call the entity to change its value. This way the entities are encapsulated inside the aggregate and they cannot be accessed directly from outside it.
But using this implementation of the state pattern it's the entity (or value object, I don't know how to call the state) who changes the aggregate. You can even use the enum directly and call an operation inside it passing your aggregate and the aggregate would be changed.
Another question about this is; the moment you have to provide some behaviour to your aggregate that depends on the current state, where do you do the implementation? Inside the aggregate, adding more operations to the base class of the state to check if the state is one or the other? Or inside the state, so the state uses the aggregate to call the different methods that it exposes to provide that functionality? The first approach would mean that, depending on the number of states you have, you would have create many methods just to check if you are in the correct state for your purposes. The other one would imply that is again the state who coordinates the way the aggregate has to call its internals.
Sorry if this question has being asked before. I've looking for days and I couldn't find something similar to what I'm asking here.
Thanks in advance.
EDIT:
Sorry for the late response, I was on holidays.
In my case the states are rather simple. They would reflect the different states of a tournament (NEW, OPEN_REGISTRATION, CLOSED_REGISTRATION, IN_PROGRESS, FINISHED, CANCELLED). What I'm trying to do is a probe of concept following the approach from the link I provided.
My question here is: the moment the aggregate (context) has to do something that depends on the state (like register a player), where would you hold that logic? Inside the context, checking first if the state class is of type OpenRegistrationState? Or inside the state classes, providing an implementation inside the OpenRegistrationState that stores the player into the context (the method would expect both the context and the player as parameters) and throwing and exception from the other ones?
It seems like using the second approach, the logic inside the context is quite simple, it only has to call the current state to do the job for it. The problem is, the moment you have many different methods that relies on the state to operate, your state classes would have an explosion of different methods that only one or two of them would implement while the other ones would throw an exception. In that case, I don't know if it would be easier to forget about the state pattern and just use an enum and check the value whenever some logic depends on the current state.
The state pattern's context says that an object's behavior is dependent on its state, and its methods contain if/then (or case) logic reflecting conditions based on states. The pattern provides an alternative to those case statements.
The solution is to create classes for each state, implementing a common interface. State-dependent operations are delegated from the context object to its current state object. The context object points to a state object that reflects its current state.
So, if I understand your question, then Domain objects (à la DDD) are the context objects and you want to avoid case logic in them. Otherwise, you don't need the state pattern (and you can stop reading now if you want, since the rest doesn't apply).
Craig Larman's Applying UML and Patterns 3rd Edition book has a chapter on Designing a Persistence Framework with Patterns and a section on Transactional States and the State Pattern. I believe his approach is compatible with DDD as it has been defined here. Actually, it's a variant of the PersistentObject idea from Scott Ambler
Domain classes have state. In this example, the states are about persistence: New, OldClean, OldDirty, OldDelete and Deleted. See Larman's book for the details.
A couple of details I couldn't easily annotate on the PlantUML image above:
the PObjectState abstract class has default no-op bodies for each method (transition)
the implementations, e.g., OldDirtyState.commit(...) handle the implementation of the behavior based on state. For persistence, this makes sense since they are generally behaviors that aren't related to domain logic. A rollback of a persistent object is basically the same.
Larman has a footnote stating "Whenever a domain object class extends a technical services class, it should be pause for reflection, as it mixes architectural concerns (persistence and application logic)."
You didn't use a concrete example of what exactly the State is that you want to model, so I am not sure whether this example applies appropriately.
If your State is some cross-cutting concern that introduces unwanted coupling in your domain objects, then you have to ask yourself the question which is worse: Case logic in the Domain objects, or unwanted coupling. Designs are trade-offs and you have to pick your battles.
I have two classes, ImageMap, extending ImageView and PageView extending GLSurfaceView, I am using the ImageMap to mainly have hot spots on drawables but I also need to add a page flip/curl animation to it, in order to do that I need those two classes to act as one object, any idea how to do that?
It is totally clear to me that multiple inheritance is not allowed in java.
There is no way of really extend two classes. What you can do is:
You make a wrapper object, that holds one instance of each object. and simply do this.ImageMap.filed1 and so. This is more convenient while developing the class. This also allows you to proxy method invocations.
You define interfaces which should be implemented, and you make a new class which implements both. This is only for class that use this class to have the interface, without really caring about the implementation.
You may need both things, since the first is about "how to do it" and the second about "how it will be presented to objects that use it".
Your question is not about Android; it's about Java.
Java does not allow for multiple inheritance.
Your reasoning is inaccurate regarding the following:
in order to do that I need those two classes to act as one object
That's not the case. An 'Activity', for example, does not have to be an event handler; it's enough if your 'Activity' can have an event handler, e.g. as an inner class which can access the Activity's variables.