java设计模式之工厂模式

xiaoxiao2021-02-28  55

工厂模式是我们最常用的实例化对象模式了,是用工厂方法代替new操作的一种模式。工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象。虽然使用工厂模式可能会多做一下工作,但是会给系统带来很好的扩展性和尽量少的维护工作。

1.创建接口

public interface fruit(){ //提供抽象方法 void eat(); }

2.创建实现类

public class Apple implements fruit{ @override//重写接口方法 public void eat(){ System.out.println("吃苹果"); } } public class Orange implements fruit{ @override//重写接口方法 public void eat(){ System.out.println("吃橘子"); } }

3.创建工厂类

工厂类的作用是根据不同的参数完成对象的实例化

public class FactoryDemo{ //获取水果的方法 public fruit getFruit(String fruitname){ //依据参数进行判断 if("apple".equalsIgnoreCase(fruitname)){ return new Apple(); } if("orange".equalsIgnoreCase(fruitname)){ return new Orange(); } return null; } }

4.调用工厂类

//测试类 public class Test{ public static void main(String[] args){ //创建工厂对象 FactoryDemo factory = new FactoryDemo(); //调用方法返回对象 Fruit fruit1 = factory.getFruit("apple"); fruit1.eat(); Fruit fruit2 = factory.getFruit("orange"); fruit2.eat(); } }

 

 

 

 

转载请注明原文地址: https://www.6miu.com/read-2626523.html

最新回复(0)