JAVA设计模式:工厂模式之抽象工厂

抽象工厂模式的好处:
当增加需求的时候,不需要修改源代码,只需定义一个类实现Play接口,定义一个工厂类实现PlayFactory 即 定义类实现顶级接口,定义工厂类实现特定的接口
代码:

/**
 * 定义一个接口:
 * 方法:玩游戏
 */
package ac.bcc.cn.interf;

public interface Play {
    /**
     * 玩的方法
     */
    public abstract void paly();
}
/**
 *此类实现Play接口
 */
package ac.bcc.cn.clas;

import ac.bcc.cn.interf.Play;

public class PlayBasketBale implements Play {

    @Override
    public void paly() {
        System.out.println("正在打篮球");
    }

}
/**
 * 此类实现Play接口
 */
package ac.bcc.cn.clas;

import ac.bcc.cn.interf.Play;

public class PlayComputer implements Play{

    @Override
    public void paly() {
        System.out.println("正在打LOL");
    }

}
/**
 * 工厂类:使用多态,创建对象  
 * 实现了PlayFactory接口
 */
package ac.bcc.cn.factory;

import ac.bcc.cn.clas.PlayBasketBale;
import ac.bcc.cn.interf.Play;
import ac.bcc.cn.interf.PlayFactory;

public class BaseketBallGameFactory implements PlayFactory{

    @Override
    public Play creatInstance() {
        return new PlayBasketBale();
    }

}
/**
 * 工厂类:使用多态,创建对象
 * 实现了PlayFactory接口
 */
package ac.bcc.cn.factory;

import ac.bcc.cn.clas.PlayComputer;
import ac.bcc.cn.interf.Play;
import ac.bcc.cn.interf.PlayFactory;

public class ComputerGameFactory implements PlayFactory{

    @Override
    public Play creatInstance() {
        return new PlayComputer();
    }

}
/**
 * 测试类
 */
package ac.bcc.cn.test;

import ac.bcc.cn.factory.BaseketBallGameFactory;
import ac.bcc.cn.factory.ComputerGameFactory;
import ac.bcc.cn.interf.Play;

public class Test {
    public static void main(String[] args) {
        //通过ballGameFactory工厂,获取打电子游戏对象
        BaseketBallGameFactory ballGameFactory = new BaseketBallGameFactory();
        Play bask = ballGameFactory.creatInstance();
        bask.paly();
        //通过computerGameFactory工厂,获取打电子游戏对象
        ComputerGameFactory computerGameFactory = new ComputerGameFactory();
        Play computer = computerGameFactory.creatInstance();
        computer.paly();
    }
}

结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值