本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/46400991
本文主要介绍简单工厂模式,主要通过代码的形式进行展示,对于程序员来说我想观看代码进行理解比文档来的直接和快些。
简单工厂模式(simple factory)是类的创建模式,又叫静态工厂方法(static factory method)模式。
简单工厂模式就是由一个工厂类根据传入的参数决定创建哪一种的产品类。
通过以下代码对简单工厂模式进行理解:
抽象产品角色:
package com.design.factory; //抽象产品角色 public interface Car { public void run(); public void start(); }
具体产品角色:
package com.design.factory; public class Benchi implements Car { @Override public void run() { System.err.println("Benchi run"); } @Override public void start() { System.err.println("Benchi start"); } }
package com.design.factory; public class Biyadi implements Car { @Override public void run() { System.err.println("Biyadi run"); } @Override public void start() { System.err.println("Biyadi start"); } }
package com.design.factory; public class Dazhong implements Car { @Override public void run() { System.err.println("dazhong run"); } @Override public void start() { System.err.println("dazhong start"); } }
工厂类角色:
package com.design.factory; public class Factory { public static Car getInstance(String clazz) { Car car = null; try { car = (Car) Class.forName("com.design.factory." + clazz) .newInstance(); } catch (Exception e) { throw new RuntimeException(e); } return car; } }
客户端测试:
package com.design.factory; public class Test { public static void main(String[] args) { Car Benchi = Factory.getInstance("Benchi"); Benchi.run(); Benchi.start(); System.err.println("------------"); Car Biyadi = Factory.getInstance("Biyadi"); Biyadi.run(); Biyadi.start(); System.err.println("------------"); Car Dazhong = Factory.getInstance("Dazhong"); Dazhong.run(); Dazhong.start(); } }
测试结果:
Benchi run
Benchi start
------------
Biyadi run
Biyadi start
------------
dazhong run
dazhong start
时间: 2024-10-04 01:18:06