AbstractFactory

本文通过一个游戏环境创建的例子介绍了抽象工厂模式的应用。该模式定义了用于创建一族相关或相互依赖对象的接口,而无需指定它们具体的类。文章展示了如何使用抽象工厂模式来创建不同类型的游戏元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package designPatterns;

import junit.framework.*;

interface Obstacle {

    
void action();

}


interface Player {

    
void interactWith(Obstacle o);

}


class Kitty implements Player {

    
public void interactWith(Obstacle ob) {

        System.out.print(
"Kitty has encountered a ");

        ob.action();

    }


}


class KungFuGuy implements Player {

    
public void interactWith(Obstacle ob) {

        System.out.print(
"KungFuGuy now battles a ");

        ob.action();

    }


}


class Puzzle implements Obstacle {

    
public void action() {

        System.out.println(
"Puzzle");

    }


}


class NastyWeapon implements Obstacle {

    
public void action() {

        System.out.println(
"NastyWeapon");

    }


}


// The Abstract Factory:

interface GameElementFactory {

    Player makePlayer();

    Obstacle makeObstacle();

}


// Concrete factories:

class KittiesAndPuzzles

implements GameElementFactory {

    
public Player makePlayer() {

        
return new Kitty();

    }


    
public Obstacle makeObstacle() {

        
return new Puzzle();

    }


}


class KillAndDismember

implements GameElementFactory {

    
public Player makePlayer() {

        
return new KungFuGuy();

    }


    
public Obstacle makeObstacle() {

        
return new NastyWeapon();

    }


}


class GameEnvironment {

    
private GameElementFactory gef;

    
private Player p;

    
private Obstacle ob;

    
public GameEnvironment(

    GameElementFactory factory) 
{

        gef 
= factory;

        p 
= factory.makePlayer();

        ob 
= factory.makeObstacle();

    }


    
public void play() {
        p.interactWith(ob);
    }


}


public class AbstractFactoryTest extends TestCase {

    GameElementFactory

    kp 
= new KittiesAndPuzzles(),

    kd 
= new KillAndDismember();

    GameEnvironment

    g1 
= new GameEnvironment(kp),

    g2 
= new GameEnvironment(kd);

    
// These just ensure no exceptions are thrown:

    
public void test1() {
        g1.play();
    }


    
public void test2() {
        g2.play();
    }


    
public static void main(String args[]) {

        junit.textui.TestRunner.run(AbstractFactoryTest.
class);

    }


}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值