Java设计模式之工厂模式基础必学篇

16 篇文章 0 订阅
2 篇文章 0 订阅

前言
工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

工厂模式场景:
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
传入参数为0,返回hello
传入参数为1,返回World
传入参数为2,返回java
我们将创建一个 StrInterface 接口和实现 StrInterface 接口的实体类。下一步是定义工厂类 Factory。
TestDemo测试类main方法中使用 Factory来获取 StrInterface 对象。它将向 Factory 传入参数(0 / 1/ 2),根据入参返回(hello / word / java)。

Java代码实现

//抽象接口类
public interface StrInterface {    
    public String get();
}
​
​
​
//hello类
public class Hello implements StrInterface{    
    //实现并重写父类的get()方法
    public String get() {
        return "hello";
    }
}
​
​
​
//World类
public class World implements StrInterface{    
    //实现并重写父类的get()方法
    public String get() {
        return "world";
    }
}
​
​
//java类
public class Java implements StrInterface{
    //实现并重写父类的get()方法
    public String get() {
        return "java";
    }
}//工厂类
public class Factory {
    
    public static StrInterface getStr(int param) {
        StrInterface str = null;
        if (0 == param) {
            str = new Hello();
        } else if (1 == param) {
            str = new World();
        } else if (2 == param) {
            str = new Java();
        }
        return str;
    }
}public class TestDemo {
	//main方法
	public static void main(String[] args) {
	    StrInterface hello = Factory.getStr(0);
	    System.out.println(hello.get());
	    StrInterface world= Factory.getStr(1);
	    System.out.println(world.get());
	    StrInterface java = Factory.getStr(2);
	    System.out.println(java.get());
	}
}

代码执行结果:
hello
world
java

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值