Git Product home page Git Product logo

head-first-design-patterns's People

Contributors

bethrobson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

head-first-design-patterns's Issues

Observer pattern code seem to be incorrect with example output

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
...

State Pattern/State Winner, has a bug in GumballMachine.java

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;
}

GarageDoorDownCommand.execute() raises "up" the door.

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.

Composite Iterator with PHP

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?

Image Proxy has a code section duplicated twice

retrievalThread = new Thread(() -> { try { setImageIcon(new ImageIcon(imageURL, "Album Cover")); c.repaint(); } catch (Exception e) { e.printStackTrace(); } }); retrievalThread.start();

BurgerAndFriesOrder not implemented

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.

Composite Iterator has different code when I did it in C#

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

License

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.

The BPM display bugs of BeatModel.java and HeartModel.java in MVC compound pattern

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

Menu.createIterator is one-shot iterator only

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

Command Pattern, Diner with Lambda, Exception java.lang.NullPointerException

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();

Cannot push on forked repository

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?

Copy + Paste mistake

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.

In java proxy example, bad usage of java.lang.IllegalAccessException

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.

Question of ArrayList type in Iterator Pattern

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.

Waitress Class java.util.Iterator Refactor page 336

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

A mistake of HasQuarterState.java in gumballstate and gumballstatewinner

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".

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.