public class Elevator ()
{
Button firstFloorbutton = ButtonFactory.getButtonInstance(this, 1);
Button secondFloorbutton = ButtonFactory.getButtonInstance(this, 2);
Button thirdFloorbutton = ButtonFactory.getButtonInstance(this, 3);
Button fourthFloorbutton = ButtonFactory.getButtonInstance(this, 4);
Fan fan1 = FanFactory.getFanInstance(this);
Light light1 = LightFactory.getInstance(this);
private void goUp()
{
.....
}
private void goDown()
{
......
}
.............
}
============================
public class Button()
{
Elevator E;
int floor;
public button (Elevator E, int floor )
{
this.E = E;
this.floor = floor;
}
public void buttonPressed()
{
//logic to determine which floor the elevator is currently at and determine whether to go up or down to reach "this.floor"
E.goUp(); // if need to go up
else
E.goDown() // if need to go down
}
}
==========================
public class ButtonFactory()
{
public Button getButtonInstance(Elevator E, int floor)
{
Button b =new Button(E, floor);
return b;
}
}
==================
public class FanFactory(){ .................}
=====================
public class LightFactory() { ........... }
==========================
What kind of relationship exist between the Elevator and Button class?
According to Kathy and Bert (SCJP) page 92 : HAS-A relationship are based on usage rather than inheritance. In other words, class A HAS-A B if code in class A has a reference to an instance of class B.
In my example Elevator class code have a reference to a instance of Button and Button have a reference to instance of Elevator class.
Can anyone please clarify on this.
The Elevator has a button. Actually, it has four, but with each of those buttons, there's a has-a relationship.
Has-a is a somewhat informal term used to refer to two more formal kinds of relationship: association and aggregation. In both cases, one party in the relationship has a pointer to the other, but they're distinguished by semantics: in an association relationship, the first party knows about the other, but doesn't completely dominate it (think you and a colleague, or a boss, or a subordinate), whereas in an aggregation relationship, the latter party is part of the former party, and has no independent existence (think you and your liver). In this case, i'd say the Button is more specifically on the subordinate end of an aggregation relationship with the Elevator, not merely an association relationship.
Other examples of association might be a Customer and a Salesman, or a Department and an Employee. Of aggregation, an Order and and OrderLine, or a Structure and a Component. Interesting corner cases are a Category and a Product, and an Order and an Invoice.
One practical consequence of the kind of relationship is object lifetime: in an association, if the first object dies, the second may live, but in an aggregation, it will die. Think about your Elevator: if you deleted one (or removed it from your live data structures and let it be garbage collected, at least), would you want the Buttons to survive?
It is a Has-A relationship, which is a simple way of remember the composition model. Button class is composed of Elevator class; i.e. Button class has a Elevator class.
Related
This might be more of a Java question, but how would you access values (say from a textfield) of a given view/class from a different class? For example if there was a TextField t1 that is in the MainView, and I wanted to get its current value for a computation in a different class. And is there a more Vaadin-specific approach here?
That can depend on the use case specifically. Since you mentioned a TextField value I assume the value is not yet stored in the DB, it's just on the UI yet -> I rule out singleton spring services.
A few ideas:
If the MainView and the different class are nested components and it's viable and not really complicated across a lot of classes... then probably passing it down the way when creating the sub-component. This is a naive solution - it can get pretty messy.
MainView() {
var t1 = new TextField();
var d = new Different(t1);
}
Fire and listen to Vaadin Component events. If you want really loose coupling, the most universal would be to use the UI instance as the event bus.
// listen in different class
ComponentUtil.addListener(attachEvent.getUI(), CloseMenuEvent.class, e -> closeMenu());
// fire change in MainView
ComponentUtil.fireEvent(ui, new CloseMenuEvent(ui))
A more specific version of number 2. is to pass the ValueChangeListener of the MainView's t1 to the different class.
MainView() {
var t1 = new TextField();
var d = new DifferentClass();
t1.addValueChangeListener(d::t1Changed)
add(t1, d);
}
Extract the common field to a third party, to a third class. Use a #UIScoped spring bean (#SpringComponent, #Service, ...) that will hold that field, and inject it to both MainView and the different class.
#Route
public class MainView extends VerticalLayout {
public MainView(Model m, Different d) {
add(m.t1, d);
}
}
#Scope(SCOPE_PROTOTYPE)
public class Different extends Component {
public Different(Model m) {
// something with m.t1
}
}
#UIScoped
public class Model {
public final TextField t1 = new TextField(); // TODO use getter
}
You could change the 4th approach by keeping String in Model and having a value change listener that updates it.
I was under the impression that the main reason for using singletons was to make sure that only one instance could be created in a program. I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.
In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.
What makes a singleton different than a regular class if it lets you create multiple instances?
// singleton class
class Car {
static let sharedCar = Car()
func run(){
print("Running")
}
}
// use
Car.sharedCar.run()
// other instances- I was expecting an error here
var jetta = Car()
jetta.run()
var cobalt = Car()
cobalt.run()
What am I missing here, can someone explain singletons?
I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.
There is no language feature called "singleton", it is an idiomatic pattern. If you leave your implementation of singleton open for instantiations from outside, there is nothing the compiler can do about that.
In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.
You should add a private init to make sure there are no external instantiations:
class Car {
static let sharedCar = Car()
func run(){
print("Running")
}
private init() {
}
}
Now you are the only one who can instantiate your class. Users of Car class outside of your code are forced to rely on sharedCar instance that you create for them.
I have the following example where CarTypeTesla is an enum value.
Car *car = [Car carOfType:CarTypeTesla];
+ (instanceType)carOfType: does an enum check and returns an instance of a given Car subclass, like this:
+ (instanceType)carOfType:(CarType)carType {
switch (carType) {
case: CarTypeTesla: {
return [[Tesla alloc] init];
}
case: CarTypeMustang: {
return [[Mustang alloc] init];
}
}
}
So that back in the main file something like this can be done (And I don't have to expose my Tesla, Mustang, and 20 other subclasses):
Car *car = [Car carOfType:CarTypeTesla];
NSLog(#"%#", car.batteryChargeRemaining);
or
Car *car = [Car carOfType:CarTypeMustang];
NSLog(#"%#", car.gasFuelRemaining);
How can I use this Factory Design Pattern, to only display properties / methods related to the returned subclass based on the enum value provided (Wouldn't want to show -(float)gasFuelRemaining when using CarTypeTesla?
What you are implementing is known as a class cluster in iOS. Some framework classes, like NSArray, NSString and NSDictionary work like this (they optimise by providing different solutions based on the amount of data they hold). This allows you to have a generic, common class that's exposed to the API, while hiding all the intricate details for solutions that are not necessarily relevant for developers, including solutions that are different based on context but should behave the same. What this means is you have a generic base class with common methods that are implemented across all other hidden classes.
The way I see it you have to options:
1 - You implement all methods in all your car classes, and have them return empty values when they are not relevant, in which case your Tesla instances would return 0 for gasFuelRemaining OR
2 - You implement protocols for different types of cars, like ElectricCarProtocol and FuelCarProtocol and have a common method in your Car class called fuelRemaining that does something along the lines of this:
if ([self conformsToProtocol:#protocol(ElectricCarProtocol)]) {
return self.batteryChargeRemaining; // you might need to cast the object here
}
return self.gasFuelRemaining; // idem
Hope this helps!
class First {
String text
Second second
static constraints = {
}
}
class Second {
String name
static constraints = {
}
}
When I delete Second class object, I got an error like this:
Cannot delete or update a parent row: a foreign key constraint fails.
I want to delete only the instance of Second inside First.
You have to remove the association of Second from First (aka FK constraint) and then will be able to delete Second.
first.second = null
second.delete()
Refer removeFrom for more details when one-many & many-many relations are used.
I would like to show a series of financial transactions in a TableView.
Each Transaction consists of a Date, a Description and an Amount.
I can make this work using bindings if I treat all the cells as Text using the example shown in a reply to another question. This allows in cell editing which is my goal.
But I can't get it to work on the date and amount columns, I think I need a separate cell factory for each cell type and a possibly a separate updateItem method but I'm stuck.
Any pointers to an example or suggestions would be helpful.
You may want to check out the DataFX project at:
http://www.javafxdata.org/
and specifically the cell factories like:
http://www.javafxdata.org/javadoc/org/javafxdata/control/cell/TextFieldCellFactory.html
DataFX contains custom cell factories for several data types, tables, lists and tree views. Assuming that for example your amount has a double type, you could write something similar like that in a subclass of TableColum
(replace ??? by the class name of the class that represents a row in your table):
setCellFactory(TextFieldCellFactory.<???, Number>forTableColumn(new Callback<String,Number>(){
#Override
public Number call(String newValueStr) {
double newValue = Double.parseDouble(newValueStr);
return newValue;
}));
setOnEditCommit(new EventHandler<CellEditEvent<???, Number>>() {
#Override
public void handle(CellEditEvent<???, Number> t) {
double newValue = t.getNewValue().doubleValue();
// do something with the double value the user entered here
}
});
}
}
I hope that at least gives you some direction. I have left out Exception handling for clarity.