简体   繁体   中英

java factory and observer pattern

I have to create a app for school and I have to use both factory pattern and observer pattern. I'm having some difficulty with understanding which one of my files should be the observer and which one should be observable.

I have a class called Shoe, and have concrete classes for different types of shoes and they all extend my Shoe class. I also have a shoeFactory. I have assigned an int for the amount of shoes that should be in store and I have generated random numbers for the amount that there is now. I want the observer to simulate amount of shoes(types) sold over time.

I'm having some difficulty understanding observers and it might be that my logic is incorrect and that observers are not used for this purpose, if that is the case, please let me know because I am completely lost.

Sounds like the Shoe subclasses represent the inventory for the shoe they represent.

So the ShowFactory is the observer and it's observing the shoes. So the Shoe classes are the observable.

When a shoe is sold or added to the store, you adjust the int value. The observer notices the change and acts upon it if needed. For example if the inventory for a given shoe falls below a certain level.

You know how to make a abstract class and how to extend this class.

If not you can use this help: http://www.tutorialspoint.com/design_pattern/observer_pattern.htm

When you have your abstract class and extended classes it is very easy to make a factory for it.

An example is to find in this link: http://www.tutorialspoint.com/design_pattern/factory_pattern.htm

for your example. Yo got a class 'Shoe' and you got for example SmallShoe, MediumShoe and LargeShoe. Now, if you make a factory you make a new class called for example 'ShoeFactory' and give it a method:

public Shoe makeShoe(int shoeSize)

you can now make the implementation for it for example like this:

public class ShoeFactory {
  public static final int SMALL = 1;
  public static final int MEDIUM = 2;
  public static final int LARGE = 3;

  public Shoe makeShoe(int shoeSize) {
    switch(shoeSize) {
      case SMALL:
        return new SmallShoe();
      case MEDIUM:
        return new MediumShoe();
      case LARGE:
        return new LargeShoe();
    }
    return null;
  }

}

// main class

public static void main(String[] args) {
  ShoeFactory factory = new ShoeFactory();
  Shoe shoe = factory.makeShoe(ShoeFactory.SMALL);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM