java设计模式 之 工厂模式
工厂模式: 简单的说就是建立一个工厂类,实现对继承同一个父类的子类对像的实例化。
- Mobile.java 父类 代码如下:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Factory;
/**
*
* @author dev
*/
public interface Mobile {
public void printName();
}
- IPhoneMobile.java 代码如下:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Factory;
/**
*
* @author dev
*/
public class IPhoneMobile implements Mobile {
@Override
public void printName() {
System.out.println("我是一个iPhone手机!");
}
}
- RedRiceMobile.java 代码如下:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Factory;
/**
*
* @author dev
*/
public class RedRiceMobile implements Mobile {
@Override
public void printName() {
System.out.println("我是一个红米手机!");
}
}
- SamsungMobile.java 代码如下:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Factory;
/**
*
* @author dev
*/
public class SamsungMobile implements Mobile {
@Override
public void printName() {
System.out.println("我是一个三星手机!");
}
}
- 手机工场类 MobileFactory.java 代码如下:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Factory;
/**
*
* @author dev
*/
public class MobileFactory {
public Mobile getMobile(String typeString) {
Mobile mobile = null;
if (typeString.equals("IPhone")) {
mobile = new IPhoneMobile();
} else if (typeString.equals("RedRice")) {
mobile = new RedRiceMobile();
} else if (typeString.equals("Samsung")) {
mobile = new SamsungMobile();
}
return mobile;
}
}
- main函数如下:
public static void main(String[] args) {
// TODO code application logic here
MobileFactory mf = new MobileFactory();
String[] typeStrings = {"IPhone", "RedRice", "Samsung"};
for (String type: typeStrings) {
Mobile mobile = mf.getMobile(type);
mobile.printName();
}
}
- 运行结果如下: