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

前言
工厂模式(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

posted @ 2020-07-23 20:26  程序员小召  阅读(74)  评论(0编辑  收藏  举报