Abstract factory

package designPattern;
//Abstract factory
//定义生产各个产品的接口
class MazeFactory{

    public Maze MakeMaze()
    {
        return new Maze();
    }
    public Door MakeDoor(Room r1, Room r2)
    {
        return new Door(r1, r2);
    }
    public Room MakeRoom(int n)
    {
        return new Room(n);
    }
    public Wall MakeWall()
    {
        return new Wall();
    }
}
//client use abstract factory and abstract product
//
class MazeGame1{
    public Maze CreateMaze(MazeFactory factory)
    {
        Maze aMaze = factory.MakeMaze();
        
        Room r1 = factory.MakeRoom(1);
        Room r2 = factory.MakeRoom(2);
        
        Door theDoor = factory.MakeDoor(r1, r2);

        aMaze.AddRoom(r1);
        aMaze.AddRoom(r2);

        r1.SetSide(North, MakeWall());
        r1.SetSide(East, theDoor);
        r1.SetSide(South, MakeWall());
        r1.SetSide(West, MakeWall());
        
        r2.SetSide(North, MakeWall());
        r2.SetSide(East, MakeWall());
        r2.SetSide(South, MakeWall());
        r2.SetSide(West, theDoor);
        
        return aMaze;
    }
}
//concrete Factory make concrete product
//实现一系列的产品的创建
class EnhantedMazeFactory extends MazeFactory
{
    public Wall MakeRoom(int n)
    {
        //concrete product of room
        return new EnhantedRoom(n, CastSpell());
    }
    public Door MakeDoor(Room r1, Room r2){
        return new DoorNeedingSpell(r1, r2);
    }
    protected Spell CastSpell();
}

class BombMazeFactory extends MazeFactory{
    public Wall MakeWall()
    {
        return new BombWall();
    }
    public Room MakeRoom(int n)
    {
        return new BombRoom(n);
    }
}

public class AbstractFactory {
    public static void main(String[] args)
    {
        MazeGame1 game;
        BombMazeFactory factory;
        
        game.CreateMaze(factory);
    }
}
posted @ 2011-08-31 16:22  lidan  阅读(168)  评论(0编辑  收藏  举报