bethrobson / head-first-design-patterns Goto Github PK
View Code? Open in Web Editor NEWCode for Head First Design Patterns book (2020)
Code for Head First Design Patterns book (2020)
I found that two packages named "remote" and "remoteWL" in command pattern. What does "WL" means here ?
A readme file is appreaciated.
Hi, I have a problem with printVegetarianMenu() methos in Composite Iterator Pattern.
This is my method:
public function printVegetarianMenu()
{
$iterator = $this->allMenus->createIterator();
echo sprintf("\nVEGETARIAN MENU\n----");
while ($iterator->valid()) {
/** @var MenuComponent $menuComponent */
$menuComponent = $iterator->current();
$iterator->next();
try {
if ($menuComponent->isVegetarian()) {
$menuComponent->print();
}
} catch (\LogicException $e) {}
}
}
I do not know if it's a difference between java and PHP but my method doesn't print nothing because the while condition iterate only over menus so, obviusly the isVegetarian() method throws always an exception.
Do you have any idea about it?
Hi,
I bought the design pattern book and practice it. Then, I recognize a small mistake and want to clarify it, also want to support to help book better. From the book, page 60 and 61, we will have output as below:
Current conditions: 82.0F degrees and 70.0% humidity
Avg/Max/Min temperature = 81.0/82.0/80.0
...
Follow source from github, the output should be:
Current conditions: 82.0F degrees and 70.0% humidity
Avg/Max/Min temperature = 82.0/82.0/82.0
...
And
Current conditions: 78.0F degrees and 90.0% humidity
Avg/Max/Min temperature = 80.0/82.0/78.0
Forecast: More of the same
...
Follow source from github, the output should be:
Current conditions: 78.0F degrees and 90.0% humidity
Avg/Max/Min temperature = 78.0/78.0/78.0
Forecast: Watch out for cooler, rainy weather
...
Is there an open source license for this code? I'm in the process of working through the book and I'm writing the examples in C# and would like to post a public repository, but don't know what attribution would be needed or if that would fall under acceptable use.
Line 33, player should be tuner.
Hi,
While i was checking command pattern, i realized one small mistake in GarageDoorDownCommand under remote package. The execute method content is garageDoor.up(); it should be garageDoor.down();
Regards,
Tolga D.
On the java proxy example, when creating the owner dynamic proxy: OwnerInvocationHandler
The logic is to prevent owner to call its setGeekRating
, it is done throwing a java.lang.IllegalAccessException
, unless I misunderstood, it is a really poor choice:
IllegalAccessException
is used when trying to reflectively access something you have no right to in term of the language (i.e: trying to invoke a private method from outside).
It is also a checked exception, which means it will be wrapped in a UndeclaredThrowableException
(see InvocationHandler::invoke
javadoc)
Since I follow the exemples quite loosely I were dubious about getting an UndeclaredThrowableException
in my client code (which is not a problem on the book's examples since all exceptions are catched). I think a specific exception or even a generic RuntimeException
would be more appropriate.
We get the exception because in file
src/headfirst/designpatterns/command/dinerLambda/Customer.java
on line 12 we make just declaration of Lambda-object as a local variable, and not save the Lambda-object in instance variable "o
":
public void createOrder() {
Order o = () -> { cook.makeBurger(); cook.makeFries(); };
}
Therefore we have null
-object in file
src/headfirst/designpatterns/command/dinerLambda/Waitress.java
on line 8:
order.orderUp();
state\gumball\GumballMachine.java
Line 75: "No gumball dispensed" should be "You need to turn the crank"
state\gumballstate\HasQuarterState.java
Line 27: "No gumball dispensed" should be "You need to turn the crank"
state\gumballstatewinner\HasQuarterState.java
Line 33: "No gumball dispensed" should be "You need to turn the crank"
Just check Page 387 in the book, the dispense method when state is HAS_QUARTER
else if (state == HAS_QUARTER) {System.out.println("You need to turn the crank");}
the following warning messages of dispense method when the state is HAS_QUARTER in Chapter 10 need to be the same.
So the message "No gumball dispensed" of HAS_QUARTER state on Page 400, Page 410, Page 422 should be "You need to turn the crank".
I've forked this project into my repositories and am currently working on the project locally. After committing my changes on the local machine, I'm not able to push my changes back to my repository. Did you somehow configure it this way or do I have to change anything?
Line 8 of Head-First-Design-Patterns/src/headfirst/designpatterns/command/diner/Diner.java references the BurgerAndFriesOrder class, but the class is not implemented in the headfirst.designpatterns.command.diner package.
The book mentions on p. 336 that the "private void printMenu (Iterator iterator)" method does not need to be changed. I'm running Eclipse IDE Version: 2022-03 (4.23.0) and the interpreter will complain with a warning that " Iterator is a raw type. References to generic type Iterator should be parameterized", as well as throw an error on the "MenuItem menuItem = iterator.next();" line, stating " Type mismatch: cannot convert from Object to MenuItem".
Changing "private void printMenu (Iterator iterator)" to "private void printMenu (Iterator iterator)" remove both the warning an error and solves the problem
The execute method of the GarageDoorDownCommand
class should call garageDoor.down()
instead of garageDoor.up()
.
In the headfirst.designpatterns.command.remote
package in the RemoteLoader
class the garageDoor
could be set to slot 4 of the remoteControl
.
retrievalThread = new Thread(() -> { try { setImageIcon(new ImageIcon(imageURL, "Album Cover")); c.repaint(); } catch (Exception e) { e.printStackTrace(); } }); retrievalThread.start();
package headfirst.designpatterns.iterator.transition;
import java.util.*;
public class Waitress {
ArrayList menus;
The code in page 360 defined the ArrayList as type Menu. However, in git repo, the type is MenuItem.
As I understand, the type should be Menu. Could you please help confirm whether I am correct?
Thank you for your help in advance.
Can you please explain me, What am I missing here?
In the code file CompositeIterator.java @ https://github.com/bethrobson/Head-First-Design-Patterns/blob/master/src/headfirst/designpatterns/composite/menuiterator/CompositeIterator.java
Line number 13 has a if condition
if (hasNext()) {
It also returns null in case it doesn't have hasNext()
In order to traverse through the Menu and MenuItems I had to remove that If condition. You can see the code @ https://github.com/VikramShetty/Fundamentals/blob/master/IteratorAndComposite/CompositeEnumerator.cs
You will find the commented code from line 19th in the above file.
So my question is why is the code not recursively walking the object hierarchy when I have that If condition in my code.
Thanks in Advance. Waiting for your reply.
Vikram
The Menu.createIterator is one-shot iterator, not support re-iterating. This looks a bug to me. Could you have a chance to fix this?
public class Menu extends MenuComponent {
private Iterator iterator; // Seriously!
private List<MenuComponent> menuComponents;
...
public Iterator<MenuComponent> createIterator() {
if (iterator == null) {
iterator = new CompositeIterator(menuComponents.iterator());
}
return iterator; // the `iterator' never resets to null once it's set.
}
...
}
...
headfirst.designpatterns.composite.menuiterator
public class MenuTestDrive {
public static void main(String args[]) {
...
Waitress waitress = new Waitress(allMenus);
waitress.printVegetarianMenu();
waitress.printVegetarianMenu(); // calling printVegetarianMenu again will print nothing
}
Output is :
VEGETARIAN MENU
----
K&B's Pancake Breakfast(v), 2.99
-- Pancakes with scrambled eggs, and toast
Blueberry Pancakes(v), 3.49
-- Pancakes made with fresh blueberries, and blueberry syrup
Waffles(v), 3.59
-- Waffles, with your choice of blueberries or strawberries
Vegetarian BLT(v), 2.99
-- (Fakin') Bacon with lettuce & tomato on whole wheat
Steamed Veggies and Brown Rice(v), 3.99
-- A medly of steamed vegetables over brown rice
Pasta(v), 3.89
-- Spaghetti with Marinara Sauce, and a slice of sourdough bread
Apple Pie(v), 1.59
-- Apple pie with a flakey crust, topped with vanilla icecream
Cheesecake(v), 1.99
-- Creamy New York cheesecake, with a chocolate graham crust
Sorbet(v), 1.89
-- A scoop of raspberry and a scoop of lime
Veggie Burger and Air Fries(v), 3.99
-- Veggie burger on a whole wheat bun, lettuce, tomato, and fries
Burrito(v), 4.29
-- A large burrito, with whole pinto beans, salsa, guacamole
VEGETARIAN MENU
----
Process finished with exit code 0
state
property has null
value if the object was created with zero gumballs like: new GumballMachine(0)
Inside GumballMachine.java you have the following:
State soldOutState; // soldOutState is null
// other properties
State state = soldOutState; // state is null
public GumballMachine(int numberGumballs) {
soldOutState = new SoldOutState(this); // soldOutState has a new reference
// other code
this.count = numberGumballs;
if (numberGumballs > 0) { // if this is false, then state will still be null
state = noQuarterState;
}
}
So, to fix this it's better to add else
statement in the constructor to give state
the new soldOutState
value, like:
if (numberGumballs > 0) { // if this is false, then state will be soldOutState
state = noQuarterState;
} else {
state = soldOutState;
}
While the repository has been updated to the new edition of the book, the description of the repository is still
Code for Head First Design Patterns book (2014)
Hello!
Uhm, as the title says:
Where can I find the Updated Files/ folder you mention on the errata page?
Is the composite iterator example updated here on github?
Kind regards,
Christian
BPM display bugs in BeatModel.java
Input bpm 100, click Set, then click Start. The view will display 100, but actually the bpm is 90. And some other cases of bpm display bugs ...
Original Code
public class BeatModel implements BeatModelInterface, Runnable {
public void on() {
bpm = 90;
//notifyBPMObservers();
thread = new Thread(this);
stop = false;
thread.start();
}
public void off() {
stopBeat();
stop = true;
}
// ...
}
New Code
public class BeatModel implements BeatModelInterface, Runnable {
public void on() {
bpm = 90;
notifyBPMObservers();
thread = new Thread(this);
stop = false;
thread.start();
}
public void off() {
stopBeat();
stop = true;
bpm = 0;
notifyBPMObservers();
}
// ...
}
BPM display bugs in HeartModel.java
Since bpmOutputLabel is null in DJView.java on startup, the bpmOutputLabel will display "offline" for a short time if the heart rate doesn't change on startup.
For example, the heart rate is 60 on startup, lastrate is -1, rate != lastrate, then lastrate = rate = 60, and notifies the view to update bpmOutputLabel. But the bpmOutputLabel is null, no update. If the rate is 60 and doesn't change for a short time, since lastrate has already changed to 60, the bpmOutputLabel will not be updated for a short time too.
Original Code
if (rate < 120 && rate > 50) {
time += change;
notifyBeatObservers();
if (rate != lastrate) {
lastrate = rate;
notifyBPMObservers();
}
}
// ...
New Code
if (rate < 120 && rate > 50) {
time += change;
notifyBeatObservers();
notifyBPMObservers();
}
// ...
And delete int lastrate = -1;
in Line 19
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.