您的位置:首页 > 其它

设计模式之抽象工厂模式的学习心得

2017-06-23 16:24 441 查看
对于抽象工厂模式,我们首先要明白的是——其是建立在工厂模式基础之上的,其也属于创建型设计模式。

在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显示指定它们的类,每个生成的工厂都能按照工厂模式提供对象。

理解:创建抽象工厂类来获取工厂对象,创建继承抽象类的工厂类,生成实体类对象以及创建一个工厂创造器来获取工厂。

思路:

1.创建抽象工厂族类;

2.创建工厂接口;

3.创建抽象工厂族子类和实现工厂接口类;

4.创建个工厂创造器/生成器类,通过字符串来获取工厂;

5.设计public类,通过main实现调用。

具体设计:

1.设计抽象工厂族类AbstractFactory,其中抽象方法名为getBall、getFruit,返回值分别为Ball和Fruit;

2.设计名为Ball和Fruit俩个接口,其中Ball接口内的方法为play,返回值为void,Fruit接口内的方法为eat(),返回值为void;

3.分别设计三个具体实现Ball接口的类:Baseball、Basketball和Football;三个具体实现Fruit接口的类:Apple、Orange和Pear;

4.设计两个继承抽象类的子类,分别基于给定的信息生成实体类对象:BallFactory和FruitFactory;

5.设计工厂生成器FactoryProducer来获取具体工厂;

6.设计public类AbstractFactoryDemo来实现调用过程。

具体代码模块:

1.抽象类AbstractFactory:

abstract class AbstractFactory{
abstract Ball getBall(String ball);
abstract Fruit getFruit(String fruit);
}
2.接口Ball和Fruit:
interface Ball{
void play();
}

interface Fruit{
void eat();
}
3.实现接口类:

class Baseball implements Ball{
public void play(){
System.out.println("棒球");
}
}

class Basketball implements Ball{
public void play(){
System.out.println("篮球");
}
}
class Football implements Ball{
public void play(){
System.out.println("足球");
}
}
class Apple implements Fruit{
public void eat(){
System.out.println("苹果");
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("橘子");
}
}
class Pear implements Fruit{
public void eat(){
System.out.println("梨");
}
}
4.设计基础抽象类的两个子类BallFactory和FruitFactory:<
4000
/p>

class BallFactory extends AbstractFactory{
public Ball getBall(String BallType){
if(BallType==null){
return null;
}
if(BallType=="篮球"){
return new Basketball();
}else if(BallType=="棒球"){
return new Baseball();
}else if(BallType=="足球"){
return new Football();
}
return null;
}
public Fruit getFtuit(String FruitType){
return null;
}
}



class FruitFactory extends AbstractFactory{
public Fruit getFruit(String FruitType){
if(FruitType==null){
return null;
}
if(FruitType=="苹果"){
return new Apple();
}else if(FruitType=="橘子"){
return new Orange();
}else if(FruitType=="梨"){
return new Pear();
}
return null;
}
public Ball getBall(String BallType){
return null;
}
}

5.工厂制造类FactoryProducer:

class FactoryProducer{
public static AbstractFactory getFactory(String factory){
if(factory=="球"){
return new BallFactory();
}else if(factory=="水果"){
return new FruitFactory();
}
return null;
}

   6.public主类AbstractFactoryDemo来实现调用:
public class AbstractFactoryDemo{
public static void main(String[] args){
AbstractFactory af1=FactoryProducer.getFactory("水果");
Fruit f1=af1.getFruit("苹果");
f1.eat();
}
}

总结:抽象工厂模式的实现可以划分两部分:第一部分即是对工厂的处理;第二部分即是对工厂内部具体的处理;最后再从顶向下的调用即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: