软件模式--工厂方法:

概念:
定义一个用于创建对象的接口,但是让其子类决定将哪个类实例化。工厂方法模式让一个类的实例化延迟到其子类。
案例:
当人们的生活水平日益提高,汽车成为人们的日益寻求的必需品。现在通过工厂方法的模式,让人们可以选购到自己需要的汽车。
类图:
在这里插入图片描述
代码实现:
car接口:

public interface Car {
    public String brand();
}

BMWCar类:

public class BMWCar implements Car{
    @Override
    public String brand() {
        return "开宝马汽车上班";
    }
}

HondaCar类:

public class HondaCar implements Car{
    @Override
    public String brand() {
        return "开本田汽车上班";
    }
}

CarFactory类:

public interface CarFactory {
    public String makeCar();
}

BMWCarFatory类:

public class BMWCarFactory implements  CarFactory{
    @Override
    public String makeCar() {
        return new BMWCar().brand();
    }
}

HondaCarFactory类:

public class HondaCarFactory implements CarFactory{
    @Override
    public String makeCar() {
        return new HondaCar().brand();
    }
}

这里通过配置文件,和spring实现Client类:
beans.xml在这里插入图片描述
Client类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
    public static void main(String[] args) {
        //构造函数参数为配置文件名称
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        CarFactory carFactory=(CarFactory)applicationContext.getBean("bmwcarfactory");
        System.out.println(carFactory.makeCar());
    }

结果:
在这里插入图片描述

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
    public static void main(String[] args) {
        //构造函数参数为配置文件名称
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        CarFactory carFactory=(CarFactory)applicationContext.getBean("hondacarfactory");
        System.out.println(carFactory.makeCar());
    }

结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值