论坛首页 Java企业应用论坛

设计模式学习笔记JAVA 03(工厂模式)—2014_3_28

浏览 20009 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-03-28   最后修改:2014-03-28

*********************************

简单工厂模式的引入

 

为什么要引入

*********************************

披萨店 成长的烦恼                                                   

 

程序编得好,要饭要到老。

 

小明不信邪,决定开一家 披萨店。

 


 

then you’d add some code that determines the appropriate type of pizza and then goes about making the pizza:

 

We’re now passing in the type of pizza to orderPizza.

 

Based on the type of pizza, we instantiate the correct concrete class and assign it to the pizza instance variable.

Note that each pizza here has to implement the Pizza interface.

 

Once we have a Pizza, we prepare it (you know, roll the dough, put on the sauce and add the toppings & cheese),then we bake it, cut it and box it!
Each Pizza subtype (CheesePizza, VeggiePizza, etc.) knows how to prepare itself.

 

 

But the pressure is on to add more pizza t ypes                                                

 

You realize that all of your competitors have added a couple of trendy pizzas to their menus: the Clam Pizza and the Veggie Pizza.



 

This code is NOT closed for modification.

If the Pizza Shop changes its pizza offerings, we have to get into this code and modify it.

 

Clearly, dealing with which concrete class is instantiated is really messing up our orderPizza() method and preventing it from being closed for modification.

But now that we know what is varying and what isn’t, it’s probably time to encapsulate it.

 

 

Encapsulating object creation                                                                                      

 

So now we know we’d be better off moving the object creation out of the orderPizza() method.

But how? Well, what we’re going to do is take the creation code and move it out into another object that is only going to be concerned with
creating pizzas.



 

Factories handle the details of object creation.

Once we have a SimplePizzaFactory, our orderPizza() method just becomes a client of that object.

Any time it needs a pizza it asks the pizza factory to make one.

 

We’ve still got a few details to fill in here; for instance, what does the orderPizza() method replace its creation code with?

Let’s implement a simple factory for the pizza store and find out

 

 

Building a simple pizza factory                                                                                            

 

What we’re going to do is define a class that encapsulates the object creation for all pizzas. Here it is...



 

Here’s our new class, the SimplePizzaFactory. It has one job in life: creating pizzas for its clients.

 

First we define a createPizza() method in the factory. This is the method all clients will use to instantiate new objects

 

 

Reworking the PizzaStore class                                                                                      

 

Now it’s time to fix up our client code. What we want to do is rely on the factory to create the pizzas for us. Here are the changes:



 

Now we give PizzaStore a reference to a SimplePizzaFactory.

 

PizzaStore gets the factory passed to it in the constructor.

 

And the orderPizza() method uses thefactory to create its pizzas by simply passing on the type of the order.

 

  • 大小: 39.7 KB
  • 大小: 53.9 KB
  • 大小: 58.8 KB
  • 大小: 75.8 KB
  • 大小: 64.7 KB
   发表时间:2014-03-29  

**************************

简单工厂是什么?

 

*************************

 

http://blog.csdn.net/weiwenlongll/article/details/6918164

 

简单工厂模式解释:                                                       

简单工厂模式(Simple Factory Pattern)属于类的创新型模式,又叫静态工厂方法模式(Static FactoryMethod Pattern),是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。

简单工厂模式的UML图: 

       简单工厂模式中包含的角色及其相应的职责如下:

       工厂角色(Creator):这是简单工厂模式的核心,由它负责创建所有的类的内部逻辑。当然工厂类必须能够被外界调用,创建所需要的产品对象。

       抽象(Product)产品角色:简单工厂模式所创建的所有对象的父类,注意,这里的父类可以是接口也可以是抽象类,它负责描述所有实例所共有的公共接口。

       具体产品(Concrete Product)角色:简单工厂所创建的具体实例对象,这些具体的产品往往都拥有共同的父类。



 
 

Think of Simple Factory as a warm up.

Next, we’ll explore two heavy duty patterns that are both factories. But don’t worry, there’s more pizza to come!

 

 

  • 大小: 44.4 KB
  • 大小: 8.7 KB
0 请登录后投票
   发表时间:2014-03-29  

***********************************

开连锁店了

 

***********************************

 

小明的披萨店,自从包子来吃过后,声名大噪,蒸蒸日上。自愿加盟的人越来越多。

 

记住,小明不在中国,国内没有任何代理。广西、安徽等地的连锁经营均属传销。

冒牌样品如下(看来是下过功夫的):

 

 

Franchising the pizza store                                        

 

Each franchise might want to offer different styles of pizzas (New York, Chicago, and California, to name a few), depending on where the franchise store is located and the tastes of the local pizza connoisseurs.
 

 

One franchise wants a factory that makes NY style pizzas:
thin crust, tasty sauce and just a little cheese.

 

Another franchise wants a factory that makes Chicago style pizzas;

their customers like pizzas with thick crust, rich sauce, and tons of cheese.

 

You want all the franchise pizza stores to leverage your PizzaStore code, so the pizzas are prepared in the same way.

 

We’ve seen one approach...

 

看上面的标题,就知道这个方法是当炮灰用的。

 

If we take out SimplePizzaFactory and create three different factories, NYPizzaFactory, ChicagoPizzaFactory and CaliforniaPizzaFactory, then we can just compose the PizzaStore with the appropriate factory and a franchise is good to go.

That’s one approach.

 

Let’s see what that would look like...

NYPizzaFactory nyFactory = new NYPizzaFactory();
PizzaStore nyStore = new PizzaStore(nyFactory);
nyStore.order(“Veggie”);

 

ChicagoPizzaFactory chicagoFactory = new ChicagoPizzaFactory();
PizzaStore chicagoStore = new PizzaStore(chicagoFactory);
chicagoStore.order(“Veggie”);

 

But you’d like a little more qualit y control...                                

 

So you test marketed the SimpleFactory idea, and what you found was that the franchises were using your factory to create pizzas, but starting to employ their own home grown procedures for the rest of the process:

they’d bake things a little differently, they’d forget to cut the pizza and they’d use third-party boxes.

 

Rethinking the problem a bit, you see that what you’d really like to do is create a framework that ties the store and the pizza creation together, yet still allows things to remain flexible.

 

In our early code, before the SimplePizzaFactory, we had the pizza-making code tied to the PizzaStore, but it wasn’t flexible.

So, how can we have our pizza and eat it too?

 

A framework for the pizza store                                                  

 

一看标题,就知道主角登场了。

 

There is a way to localize all the pizza making activities to the PizzaStore class, and yet give the franchises freedom to have their own regional style.



 

Now createPizza is back to being a call to a method in the PizzaStore rather than on a factory object.

 

Now we’ve got a store waiting for subclasses; we’re going to have a subclass for each regional type (NYPizzaStore, ChicagoPizzaStore,
CaliforniaPizzaStore) and each subclass is going to make the decision about what makes up a pizza.

 

 

Allowing the subclasses to decide                                                

 

Remember, the PizzaStore already has a well-honed order system in the orderPizza() method and you want to ensure that it’s consistent across all franchises.

 

What varies among the regional PizzaStores is the style of pizzas they make – New York Pizza has thin crust, Chicago Pizza has thick, and so on – and we are going to push all these variations into the createPizza() method and make it responsible for creating the right kind of pizza.

 

The way we do this is by letting each subclass of PizzaStore define what the createPizza() method looks like. So, we will have a number of concrete subclasses of PizzaStore, each with its own pizza variations, all fi tting within the PizzaStore framework and still making use of the well-tuned orderPizza() method.



 

Each subclass overrides the createPizza() method, while all subclasses make use of the orderPizza() method defined in PizzaStore.

We could make the orderPizza() method final if we really wanted to enforce this.

 

If a franchise wants NY style pizzas for its customers, it uses the NY subclass, which has its own createPizza() method, creating NY style pizzas

public Pizza createPizza(type) {
if (type.equals(“cheese”)) {
pizza = new NYStyleCheesePizza();
} else if (type.equals(“pepperoni”) {
pizza = new NYStylePepperoniPizza();
} else if (type.equals(“clam”) {
pizza = new NYStyleClamPizza();
} else if (type.equals(“veggie”) {
pizza = new NYStyleVeggiePizza();
}
}

 

  • 大小: 67.1 KB
  • 大小: 60.4 KB
  • 大小: 71 KB
  • 大小: 44.8 KB
0 请登录后投票
   发表时间:2014-03-30  

**************************************

how do subclasses decide?

 

校花的困惑

***************************************



 



 

Now, to take this a little further, the orderPizza() method does a lot of things with a pizza object (like prepare, bake, cut, box), but because Pizza is abstract, orderPizza() has no idea what real concrete classes are involved.

 

In other words, it’s decoupled!



 



 

So, is there a real-time decision that subclasses make? No, but from the perspective of orderPizza(), if you chose a NYStylePizzaStore, that subclass gets to determine which pizza is made.

So the subclasses aren’t really “deciding” – it was you who decided by choosing which store you wanted – but they do determine which kind of pizza gets made.

  • 大小: 49.3 KB
  • 大小: 57.1 KB
  • 大小: 63.2 KB
  • 大小: 33.4 KB
0 请登录后投票
   发表时间:2014-03-30  

********************************

Let’s make a PizzaStore

 

Declaring a factory method

*********************************

Being a franchise has its benefits.

You get all the PizzaStore functionality for free.

All the regional stores need to do is subclass PizzaStore and supply a createPizza() method that implements their style of Pizza.

public class NYPizzaStore extends PizzaStore {
Pizza createPizza(String item) {
if (item.equals(“cheese”)) {
return new NYStyleCheesePizza();
} else if (item.equals(“veggie”)) {
return new NYStyleVeggiePizza();
} else if (item.equals(“clam”)) {
return new NYStyleClamPizza();
} else if (item.equals(“pepperoni”)) {
return new NYStylePepperoniPizza();
} else return null;
}
}

 

createPizza() returns a Pizza, and the subclass is fully responsible for which concrete Pizza it instantiates

 

The NYPizzaStore extends PizzaStore, so it inherits the orderPizza() method (among others).

 

We’ve got to implement createPizza(), since it is abstract in PizzaStore.

 

 

With just a couple of transformations to the PizzaStore we’ve gone from having an object handle the instantiation of our concrete classes to a set of subclasses that are now taking on that responsibility.

 

public abstract class PizzaStore {
public Pizza orderPizza(String type) {
Pizza pizza;
pizza = createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
protected abstract Pizza createPizza(String type);

}

 

The subclasses of PizzaStore handle object instantiation for us in the createPizza() method.

 

0 请登录后投票
   发表时间:2014-03-31  

*************************

烧饼是怎么来的?

 

*************************

Let’s see how it works: ordering pizzas with the pizza factory method      

 




 



 



 



 
 

  • 大小: 27.4 KB
  • 大小: 65 KB
  • 大小: 43.9 KB
  • 大小: 54 KB
  • 大小: 56.5 KB
0 请登录后投票
   发表时间:2014-03-31  

************************************

PIZZA 的面貌

 

************************************

 

We’ll start with an abstract Pizza class and all the concrete pizzas will derive from this.

 


 
 

Each Pizza has a name, a type of dough, a type of sauce, and a set of toppings.

 

The abstract class provides some basic defaults for baking, cutting and boxing.

 

The Chicago style pizza also overrides the cut() method so that the pieces are cut into squares.

 

You’ve waited long enough, time for some pizzas!                                          

 

public class PizzaTestDrive {
 
	public static void main(String[] args) {
		PizzaStore nyStore = new NYPizzaStore();
		PizzaStore chicagoStore = new ChicagoPizzaStore();
 
		Pizza pizza = nyStore.orderPizza("cheese");
		System.out.println("Ethan ordered a " + pizza.getName() + "\n");
 
		pizza = chicagoStore.orderPizza("cheese");
		System.out.println("Joel ordered a " + pizza.getName() + "\n");

		pizza = nyStore.orderPizza("clam");
		System.out.println("Ethan ordered a " + pizza.getName() + "\n");
 
		pizza = chicagoStore.orderPizza("clam");
		System.out.println("Joel ordered a " + pizza.getName() + "\n");

		pizza = nyStore.orderPizza("pepperoni");
		System.out.println("Ethan ordered a " + pizza.getName() + "\n");
 
		pizza = chicagoStore.orderPizza("pepperoni");
		System.out.println("Joel ordered a " + pizza.getName() + "\n");

		pizza = nyStore.orderPizza("veggie");
		System.out.println("Ethan ordered a " + pizza.getName() + "\n");
 
		pizza = chicagoStore.orderPizza("veggie");
		System.out.println("Joel ordered a " + pizza.getName() + "\n");
	}
}

 


 
 

  • 大小: 42.4 KB
  • 大小: 37 KB
0 请登录后投票
   发表时间:2014-04-02  

********************************

来见一下 工厂模式吧

 

*********************************

已经过了好几天,有些不耐烦了。不过,想想学习是个系统工厂,就是 住房信息 联网 也要 排到 2020年前完成。 希望那时 互联网 技术没有新的 跨越,否则又要延期了。



 

All factory patterns encapsulate object creation.

The Factory Method Pattern encapsulates object creation by letting subclasses decide what objects to create.

Let’s check out these class diagrams to see who the player s are in this pattern:



 

Often the creator contains code that depends on an abstract product, which is produced by a subclass.

The creator never really knows which concrete product was produced.

It defines an abstract factory method that the subclasses implement to produce products.

 

Since each franchise gets its own subclass of PizzaStore, it’s free to create its own style of pizza by implementing createPizza().

 



 

Factories produce products, and in the PizzaStore, our product is a Pizza.

 

 

Another perspective: parallel class hierarchies                              

 

We’ve seen that the factory method provides a framework by supplying an orderPizza() method that is combined with a factory method.

Another way to look at this pattern as a framework is in the way it encapsulates product knowledge into each creator.

 



 

The NYPizzaStore encapsulates all the knowledge about how to make NY style pizzas.

The factory method is the key to encapsulating this knowledge.

  • 大小: 52 KB
  • 大小: 49.4 KB
  • 大小: 33.5 KB
  • 大小: 51.2 KB
0 请登录后投票
   发表时间:2014-04-02  

********************************

工厂 模式 真相

 

告白

*********************************

不要给我讲 什么血汗工厂 ,什么12连跳。

当然,不是,

我们要揭露工厂模式 的真相,

 

真相只有一个

 



 

As with every factory, the Factory Method Pattern gives us a way to encapsulate the instantiations of concrete types.

 

 

Looking at the class diagram below, you can see that the abstract Creator gives you an interface with a method for creating objects, also known as the “factory method.”

 

Any other methods implemented in the abstract Creator are written to operate on products produced by the factory method. Only subclasses actually implement the factory method and create products.

 

The Creator is a class that contains the implementations for all of the methods to manipulate products, except for the factory method.

The ConcreteCreator implements the factoryMethod(), which is the method that actually produces products.

 

The ConcreteCreator is responsible for creating one or more concrete products.

It is the only class that has the knowledge of how to create these products.

  • 大小: 11.2 KB
  • 大小: 35.1 KB
  • 大小: 15.6 KB
0 请登录后投票
   发表时间:2014-04-03  

****************************************

自问自答

 

对一个早期 精神分裂症患者的记录

****************************************



 



 



 



 



 



 

  • 大小: 83.6 KB
  • 大小: 20.9 KB
  • 大小: 73.2 KB
  • 大小: 90.8 KB
  • 大小: 81.4 KB
  • 大小: 107 KB
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics