How to design a resource association problem in Java - java

I have the following modeling problem:
as an exercise, I need to model a system that allocates units (police cars/fire trucks) to a specific emergency (fire/robbery/...). Therefore an emergency needs to say how many units it needs (for instance 2 fire trucks and 3 ambulances). Of course, these units need to be assigned to that emergency. I've modeled this as two abstract classes: Emergency and Unit with the real units and emergencies that inherit these classes.
Is there an elegant design so the emergency can tell in a generic way which units it needs (additional types of units and emergencies are expected)?
The programming language is Java.
I know this is probably one of the standard design patterns, but I'm quite new to these design patterns.

You have a lot of options with this. Some of the patterns that come to mind are Observer, Chain of Responsibility, and Visitor. However, a lot of non-pattern solutions seem reasonable too. Don't be hypnotized into using patterns all the time.
That being said, a combination of patterns will probably be the best solution. Create a higher level class, some sort of a Director. Allow the Director to observe the Emergencies, using the Observer pattern. When the Director receives a work request, it goes to an Object Pool and modifies the Emergency as it sees fit.

What about good ol' Java interface?
public interface HasEmergency {
public UnitType responderUnit();
public int numberOfUnitsNeeded();
}
public abstract class Resource implements HasEmergency {
// ...
}

Related

Can the Composite Design pattern avoid a Collection (List, HashTable) data structure?

I want a full comprehension of all possible types of the Composite Design Pattern when looking at code. In this code I have a composite object PeanutButterAndJellySandwich which contains Bread, PeanutButter and Jelly.
The reason PeanutButterAndJellySandwhich's field variables are all of type food is to account calories
interface Food{
int calories = 9000;
}
class Bread implements Food{
private String flour;
private String salt;
}
class Jelly implements Food{
private String fruit;
private String sugar;
}
class PeanutButter implements Food{
private boolean crunchy;
}
class PeanutButterAndJellySandwich implements Food{
private Food bread;
private Food jelly;
private Food peanutButter;
public void setBread(Bread bread){this.bread=bread;}
public void setJelly(Jelly jelly){this.jelly=jelly;}
public void setPeanutButter(PeanutButter butter){this.peanutButter=butter;}
}
Is this follow the Composite Design Pattern or does PeanutButterAndJellySandwhich need something like foodItems:ArrayList<Food>. The UML Diagram would look very similar.
I ask this because I have not found this anywhere explicitly stated after about 5 hours of searching and in the application of something like an embedded system we may not want a collection data structure since memory/storage is limited. However, all examples online are utilizing many forms of lists.
From my understanding, composite pattern is meant to allow you ignore the difference between components (Bread, Jelly, PeanutButterAndJellySandwich, etc in your case) and their hierarchy, using runtime polymorphism most likely. It's meant to let you handle them in a uniformed way (through a loop, most likely), and let the runtime do the rest.
Therefore, since your example just didn't show this intention and manually handled that, I would say this is not a composite pattern, but rather a plain (plan of) use of runtime polymorphism.
However, your code does catch the point where PeanutButterAndJellySandwich is a Food, enabling the potential future use (e.g. a PeanutButterAndJellySandwich with an ingredient PeanutButterAndJellySandwich) which is the aim of the composite pattern. (But you didn't show this intention in your code.)
p.s.
But design patterns are not something sacred. They are meant as a guide rather than a restriction.
I would say the question itself doesn't make much sense, because design patterns are not meant to save memory, but to promote good system designs. So they are described in a generic way for easier to describe and understand.
The composite pattern is used to create tree structures. In case of your sandwich it doesn't make much sense. You have just a simple layer (list) of Ingredients. Except you want to have a sandwich as part of a sandwich. To me your design is just broken. Use patterns where they apply. Don't apply patterns bcause they exist.
Strictly speaking the composite pattern as per Gamma, Helm et. al. does talk about manipulating children via the interface (in your case, Food), which would tend to lead you to an implementation in which any number of children could be added to (and removed from) any node in the composite tree. A typical implementation might include an abstract super-class that would implement children-management (add, remove etc.) and then concrete sub-types would derive off that. Some thing like this:
There are design choices i'm making here but the gist is right.
More widely, however, composition does not necessitate the composite pattern be implemented. Using composition is just fine without it, in fact there is a principle also discussed by Gamma, Helm et. al. that talks about favouring composition over inheritance and that has nothing to do with the composite pattern per se.
It's tempting to use inheritance as a handy way to reuse code in your program, but that's really not what inheritance is about, which is why composition is favoured as a way to guard against misusing inheritance and creating unmanageable code as a result. I fear this might be the case in your use of the Food interface to get to the Calories member variable. If you are not generalising your design, i.e. you want to be specific about what PeanutButterAndJellySandwich contains at design time (in the structure of your code), then what you probably should do is declare the variables inside PeanutButterAndJellySandwich using their concrete types. They are Food, there's no doubt, but consider what PeanutButterAndJellySandwich is going to do with member variables that are all declared as Food? Why bother not using an array of Food?

Using strategy pattern with simple factory

I've been learning about design patterns and I think I'm a little bit stuck with an exercise where I do not posses any answer-pages to.
I already used the strategy pattern to create this:
http://i.imgur.com/5Lia4JD.png (minus the setBehavior functions in duck)
I need to improve this design with simple factory because at the moment, the 2 types of behaviors are instantiated via following code (shown via example):
public MallardDuck()
{
setQuackBehavior(new Quack());
setFlyBehavior(new FlyWithWings());
}
This is not correct because we need to program to an interface and not to an implementation.
What I thought to do is making 2 separate factories that each handle a specific behavior but when I made the design I started doubting my solution. Is it normal to do this sort of thing with simple factory?
Could anyone push me in the correct direction? :]
If you're programming Ducks, then it's a toy example anyway. Go ahead and do the two separate simple factories. The general rule is a simple factory per interface. You could put all the simple factories in one class to make it less complex.
The disadvantage of concrete classes instantiating other concrete classes is of course the risky coupling to implementations. If the implementation details change (yes, the new is trivial but the whole ducks example is trivial), your classes that know that information are also liable to change.
You're right that it's not programming to an interface. Classes that know less about implementation details are more insulated from changes in those details, which is the whole point of using interfaces.
If you want to avoid the strong coupling between concrete strategies and their host you may rely on a factory that knows how to instantiate a Duck with the proper strategies for a given type rater than having a concrete class per type.
The above design may be slightly more testable, but I do not think you should be too concerned about the coupling between concrete ducks and the concrete strategies they use.
This is not correct because we need to program to an interface and not to an implementation.
And you program to an interface since setQuackBehavior() takes as input an interface and that your quack class represents the quack behavior field as an interface and not an implementation.
At a time, in a code, using a implementation class is normal.
Using a factory with methods returning based interface instances is useful in many cases but in your case, I don't see the interest. Why your quack subclasses should not know which concrete behavior used ?
If it has no reason, so it seems ok :
setQuackBehavior(new Quack());
Using factory with not added value gives a complex code without reasons.

Empty interfaces - Modeling of object relationships

Is it ok to use empty interfaces for object modeling?
E.g. the following interface extends other empty interfaces in order the characterize the object 'Ferry':
public interface Ferry extends Watercraft, StationBased, Scheduled, Oneway, Motorized {}
Watercraft, StationBased, etc., are all empty interfaces, too, so they kind of act as a marker. However, they are not used by the JVM or compiler. These classes are only used for modeling purposes.
Is this good practice? Should an interface not usually provide some kind of common functionality, and not merely mark a class?
Yes, you can use empty interfaces for object modeling, but... Object modeling without any use-case is IMO overstretching it.
You write code to execute concrete actions, you model it to leverage general abstractions in the domain, and yes you can over-abstract your code.
Adding an interface in code is a classification or typification, which is only necessary as long as there is a taker for it. Otherwise it is plain dead code.
My worst encounter which sometimes still haunts me in my nightmares was an abstraction over business services, which essentially replaced it with a single method taking a map as arguments and returning an object which either contained the result or an error state. Effectively modeling a method invocation, but this time without types. Having forced this down on all business methods was simply a nightmare to unravel later.
There is nothing wrong with doing it that way except that you may discover quite quickly that changing the structure or adding new forms will become unpleasant.
I would probably consider a much more flexible enum option.
enum CraftAttributes {
Watercraft,
StationBased,
Scheduled,
Oneway,
Motorized;
}
class Ferry {
Set<CraftAttributes> attributes = EnumSet.of(
CraftAttributes.Watercraft
//...
);
}
There are lots of sweet thing you can do with unions and intersections of Sets that make for powerful but lucid code.

What's the best way to handle type indicators in object-oriented design? [duplicate]

This question already has answers here:
Object-oriented design: Saving complex objects
(2 answers)
Closed 5 years ago.
We have a business model that requires, say, different types of vehicles to be identified. For example, motorcycle, boat, yacht, farm equipment, snowmobiles, heavy truck, light truck, passenger car, and "Other".
I think there are two ways to handle it: Create a Vehicle class with a few subclasses, say, boat, truck, car and have a single enum indicating the actual type. This would work, allowing you to represent vehicles that share some common features with common subclasses. But it allows you to have mismatched enums with the classes.
I think the traditional way to handle it is to have a separate subclass for each type, which may subclass the vehicle, or a subclass of vehicle. For example, heavy and light truck might subclass truck; boat and yacht might subclass boat; snowmobile might subclass vehicle. The problem is, it doesn't really lend itself to representing the concept of other.
Does anyone have any patterns or best-practices for these sorts of scenarios?
Peter
EDIT:
The purpose of the object is to convey information about the vehicle and to be able to display that information in a user-friendly way. For example, pull the data from a database and display it on a screen to be viewed/edited.
This leads to another downside to the traditional OO means that leans away from type indicators for actual types, in that to display the type one would need to perform some sort of instance-of and convert the value to something user-friendly.
(Also, clarified I was talking about a single enum, not an enum per subclass.)
I would start with a Vehicle and not add too much abstraction.
I wouldn't use the class hierarchy to describe something you could use a field to describe.
Is the code for these types so different?
For example, say you have a type you didn't think of before. like an aqua-car (which is a car which can travel over water) or a seyway, or a unicycle. You could create a new class for each type or you could have it entirely data driven with fields like
name: aqua-car
type: Exotic Car
travelsOnWater: true
travelsOdLand: true
wheels: 4
I suggest you read You Ain't Gonna Need It Better to add only the abstraction you need, not the abstraction you can imagine.
The Real Question
How different do two "things" need to be before they deserve their own class?
The Answer
It depends entirely on how you are going to use the objects.
Will you be comparing them based on some property they have (e.g., does it float?)? If so, a single class with a differentiating property makes sense.
Are you going to display your objects on an interface? Would it make sense within your application to display Light Trucks and Heavy Trucks in a single table? If they cannot meaningfully exist and be displayed as one data set, then it makes sense to have two classes.
Those are just two examples. The point is, if you create a new class, it should be useful. Java is particularly prone to over-abstraction.
What do I do about Other?
Other sounds like a group of Vehicles that are not Trucks and not Cars. It sounds like you want to catch all other Vehicles and put them in one class. Why not use the Vehicle class? Don't create another class that derives from Vehicle but adds zero functionality. The same usefulness test applies here.
Is a Vehicle useful enough to satisfy my needs for all "other" vehicles? If not, I need to create more classes.
I took your advice and created two useful classes. Now, I can't tell them apart and I refuse to use instanceof. What do I do?
No matter how abstracted your classes are, I will always be able to add instances your class to a List<Object> and will then be unable to tell them apart. You cannot bulletproof your design.
Let me put it another way - if you add Eggs and Cars to a List, and you later need to differentiate between Eggs and Cars, then there is a problem with your List, not the Eggs and Cars.
There is not simple answer for your question. Because its depend on the business logic you will have to perform with that data structure.
I would start with an interface Vehicle that will resolve a Identyficator from to get the description of concrete representant.
interface VehicleIdentyficator {
String identyficator();
}
interface Vehicle {
Identyficator getIdentyficator();
}
With this you are not limited to class, enum or other kind of design.
Then i would use class hierarchy to describe the properties of each vehicle.
After that add some logic/behavioural aspects to the code and get a look that my data structures are valid for the task.
At the end of the day the important aspect is to perform some operations.
For example there is no point of creation three classes Truck, LightTruck and HavyTruck.
You could create a class that describe them by task they perform
They can transport on ground
The Light truck can carry less load but it used to travel in small cities.
The Heavy truck is opposite to Light. Have big Range carry more load.
When we compare to this a boat we see that boat is more like light truck the only difference is that it travel on water.
So try to understand the object not be what it is but what it can do. What tasks can be performed by it and what are the limitation. Then with your design will be really close to what you need.
I hope this sentence is correct and i will repeat myself. It seams that you are using those vehicles, not constructing them. So focus on their mission to full fill not on their physical aspects.
But you can do something like this
enum VechicleType implements VehicleIdentyficator {
TRUCK("TRUCK"),
HEAVY_TRUCK("HEAVY_TRUCK")
private final String indentyficator;
private VechicleType(String indetyficator) {
this.indentyficator = identyficator;
}
public String identyficator() {
return indentyficator;
}
}
But then every time you add some new vehicle you must cover all points where such new hard coded type will be used.
As others stated, I think it depends on how you're gonna use your vehicles.
If you just need to distinguish between types at some points, but you mostly handle all vehicles the same way, go for the enum type.
If you really need to specify different behaviors and you make use of shared features/behaviors, go for a full class hierarchy. That's also my preferred approach, because I feel like it offers more evolutivity.
The best way to handle type indicators in OO development is to not have type indicators.
Type indicators are a structured programming
(that think that predates object oriented programming) concept.
In OO, type is identified by type, not by an artificial indicator.
Edit:
If you have a fixed domain of things that you must represent with an object (for example: tractor, speed boat, row boat, motorcycle, mazda 626, pickup truck, deuce-and-a-half truck) then you can (perhaps should) represent each thing with a concrete class. The interesting design question will be based on what you need to do with the objects.
If you just need to know "is this a water vehicle" or "how many wheels does this have" then use an Interface with isWaterVehicle(), getWheelCount(), isTruck() methods. Implement the interface on your objects and hard code the answer. For example:
class SpeedBoat implements VehicleInfo
{
public int getWheelCount()
{
return 0;
}
public boolean isTruck()
{
return false;
}
public boolean isWaterVehicle()
{
return true;
}
}
If you have a large number of similar objects, use an abstract class to set the defaults.
abstract class AbstractTruck implements VehicleInfo
{
public final int isTruck()
{
return true;
}
}

What is the difference between abstraction and encapsulation? [duplicate]

This question already has answers here:
Abstraction VS Information Hiding VS Encapsulation
(22 answers)
Difference between abstraction and encapsulation?
(40 answers)
Closed 2 months ago.
What exactly is the difference between encapsulation and abstraction in Java? Any brief examples would also be appreciated.
Abstraction and encapsulation are two great flavors that taste great together.
Encapsulation is minimizing what you expose to the user of your code. That "user" may be the rest of your code, or whoever uses the code you publish.
There some definite benefits to encapsulation:
The user of your code doesn't depend on parts of your program that are likely to change. When you change your program, they don't have to change their code
You are more in control of exactly how your code and state changes over the lifetime of your program. You must handle fewer scenarios, and will have fewer unexpected problems to fix
I don't know Java, but here is a small example of encapsulation in C#:
public class Giraffe
{
public Giraffe(int heightInFeet)
{
this.heightInFeet = heightInFeet;
this.numberOfSpots = heightInFeet * 72;
}
public override string ToString()
{
return "Height: " + heightInFeet + " feet"
+ " Number of Spots: " + numberOfSpots;
}
private int heightInFeet;
private int numberOfSpots;
}
Instead of exposing numberOfSpots, it is encapsulated within the class, and exposed via the ToString method.
Abstraction is using extension points to let the choice be deferred to a different part of which exact code is run. That choice could be made elsewhere in your program, in another program, or dynamically at runtime.
There are also strong benefits to abstraction:
When you change your code that implements an abstraction, the user of the abstraction doesn't have to change their code. As long as the abstraction doesn't change, the users won't have to change their code.
When you write code that uses an abstraction, you can write code once that will be reusable against any new code that implements that abstraction. You can write less code to do more.
A highly used abstraction in C# is IEnumerable. Lists, Arrays, Dictionaries, and any other type of collection class all implement IEnumerable. The foreach loop structure and the entirety of the LINQ library are based on that abstraction:
public IEnumerable<int> GetSomeCollection()
{
// This could return any type of int collection. Here it returns an array
return new int[] { 5, 12, 7, 14, 2, 3, 7, 99 };
}
IEnumerable<int> someCollectionOfInts = GetSomeCollection();
IEnumerable<string> itemsLessThanFive = from i in someCollectionOfInts
where i < 5
select i.ToString();
foreach(string item in itemsLessThanFive)
{
Console.WriteLine(item);
}
You can easily write your own abstractions, too:
public interface IAnimal
{
bool IsHealthy { get; }
void Eat(IAnimal otherAnimal);
}
public class Lion : IAnimal
{
public Lion()
{
this.isHealthy = true;
}
public bool IsHealthy
{
get { return isHealthy; }
}
void Eat(IAnimal otherAnimal)
{
if(otherAnimal.IsHealthy && !(otherAnimal is SlimeMold))
{
isHealthy = true;
}
else
{
isHealthy = false;
}
}
private bool isHealthy;
}
IAnimal someAnimal = PullAnAnimalOutOfAWoodenCrate();
Console.WriteLine("The animal is healthy?: " + someAnimal.IsHealthy);
You can use both together, as I did with IAnimal, and IsHealthy. IAnimal is an abtraction, and having only a get accessor, and no set accessor on IsHealthy is encapsulation.
These two concepts are quite different.
Abstraction is the practice of making a base class 'abstract' and then extending its functionality. An abstract class is something that doesn't exist in a concrete matter; its only purpose is to be extended. Think of if you were writing classes to represent different species. All of your different species might extend an abstract Animal class because they would all share common attributes as animals. However, you would never instantiate an Animal object, because every animal you see in the world is a squirrel, or a dog, or a fish ... or some kind of concrete implementation of that base, abstract animal class.
Encapsulation is the practice of making your class variables private, and then allowing access to them from get and set methods. The purpose of this is separate the way your data is accessed and the way it is implemented. For example, if you have some variable that has a requirement, that every time it is changed, it also increments a second variable by 1, then you would encapsulate that functionality; that way your code is more reliable because you don't have to remember to adhere that rule every time you'd access the original variable.
If you want specific code examples, I'd recommend just doing a google search, because there's a lot of examples like that available. Here's two:
http://www.tutorialspoint.com/java/java_abstraction.htm
http://www.tutorialspoint.com/java/java_encapsulation.htm
Encapsulation is to protect your member variables or methods from the outside world.
Abstraction is the way to have specific implementation. that is which implementation to use is unknown to the user.
Encapsulation is part of abstraction. The notion of abstraction is one of creating an object to represent another object. Typically, the original object is more complex than the abstraction. An abstraction is thus a representation, usually as an aid to memory, for terminology/communication etc. Think of it like this: abstract art is a representation of something else. A steering wheel, gearshift and 2/3 pedals is an abstraction of how a car works.
Basically, the abstraction allows you to represent something complex, with a lot of details, as something a lot simpler. In my opinion, this is related to 'chunking' in cognitive science. We're not able to keep complex things in our head, so we simplify by abstracting, then using the abstraction. Design Patterns are another great example. Instead of talking about details, we can talk about Command, State or Strategy pattern etc.
Encapsulation is part of forming/creating an abstraction. The smaller an object's interface, the easier it is to abstract. You don't need to know how an engine and gearbox work to drive a car, you just need to understand their abstractions (gear shift and accelerator). The details of the engine and gearbox are encapsulated (into the interface) in order to create the abstraction.
Encapsulation is needed for abstraction because an abstaction can't deal with all the real details and complexity (otherwise its not an abstraction). So the gearshift is an incomplete representation (or model) of a gearbox, but its complete enough for everyday use. Encapsulation can be thought of as 'hiding details', which is necessary for creating a simpler representation.
Its also important to discuss the concept of an 'interface'. For the most part, the terms 'interface' and 'abstraction' are more less interchangeable in this instance. An interface is the part of a system with which the user deals or interacts. The interface to a car is the steering wheel, gear shift and pedals etc. The abstraction produces an interface. You don't deal with the engine/gearbox directly, you deal with their respective interfaces.
Another reason for encapsulation is because we're dealing with an incomplete model/abstraction, we don't understand the full complexity of the original, and can't be trusted to deal with all the variables (because we don't understand the full model). This is important for decoupling, because without abstraction, interacting components would know too much about each other. Think about it, because every car has a steering wheel, pedals and gearshift, you can drive any car, regardless of engine type etc. Also, the gearbox is abstracted from the engine. Otherwise each custom engine would need a custom gearbox.
Similarly, a Class is an abstraction. The class represents some complex model, through its interface - the public members of the class. This interface is created through encapsulation. The class presents a simplified interface of its more complex implementation to its collaborators. You can also think of it as a 'need to know' situation. The collaborators of the class don't need to know exactly how it works. Just as you don't need to know how an engine works to drive a car.
Encapsulation, interfaces and abstraction play a critical role in cohesion and coupling, and therefore maintenance of your code. If you don't create good abstractions, and violate the 'need to know' principle, then your code becomes entangled, fragile and a nightmare to change, because there is no 'buffering'. The OO concept of 'tell don't ask' is also related to this.

Categories