说一下工厂模式,先看一下图:
简单来说就是我需要一个对象,new出来,具体创建过程在子类
我这里模仿了一下建造手机的过程
首先有手机这个概念,然后工厂进行具体品牌进行创建
概念:
package com.fanyafeng.factory.factory;
/**
* Created by fanyafeng on 16/7/1.
*/
public interface MobilePhone {
public void create();
}
再看一下三种手机
package com.fanyafeng.factory.mobilephone;
import com.fanyafeng.factory.factory.MobilePhone;
/**
* Created by fanyafeng on 16/7/1.
*/
public class HuaWei implements MobilePhone{
@Override
public void create() {
System.out.println("手机名称:华为");
System.out.println("--系统:ios");
System.out.println("--材料:塑料+金属");
System.out.println("--UI:EUI");
System.out.println("--存储:内部,外部");
}
}
package com.fanyafeng.factory.mobilephone;
import com.fanyafeng.factory.factory.MobilePhone;
/**
* Created by fanyafeng on 16/7/1.
*/
public class Iphone implements MobilePhone {
@Override
public void create() {
System.out.println("手机名称:苹果");
System.out.println("--系统:ios");
System.out.println("--材料:塑料+金属");
System.out.println("--屏幕:视网膜屏");
}
}
package com.fanyafeng.factory.mobilephone;
import com.fanyafeng.factory.factory.MobilePhone;
/**
* Created by fanyafeng on 16/7/1.
*/
public class Mi implements MobilePhone{
@Override
public void create() {
System.out.println("手机名称:小米");
System.out.println("--系统:ios");
System.out.println("--材料:塑料+金属");
System.out.println("--UI:MIUI");
System.out.println("--Remote:红外线");
}
}
看一下工厂
package com.fanyafeng.factory.factory;
import com.fanyafeng.factory.mobilephone.HuaWei;
import com.fanyafeng.factory.mobilephone.Iphone;
import com.fanyafeng.factory.mobilephone.Mi;
/**
* Created by fanyafeng on 16/7/1.
*/
public class MobilePhoneFactory {
public MobilePhone getMobilePhone(String mobilePhone) {
switch (mobilePhone) {
case "Iphone":
return new Iphone();
case "HuaWei":
return new HuaWei();
case "Mi":
return new Mi();
default:
return null;
}
}
}
我感觉这个return null不是很好,感觉这个null不是很受欢迎
package com.fanyafeng.factory;
import com.fanyafeng.factory.factory.MobilePhone;
import com.fanyafeng.factory.factory.MobilePhoneFactory;
import com.fanyafeng.factory.mobilephone.HuaWei;
import com.fanyafeng.factory.mobilephone.Iphone;
/**
* Created by fanyafeng on 16/7/1.
*/
public class Main {
public static void main(String[] args) {
MobilePhoneFactory mobilePhoneFactory=new MobilePhoneFactory();
MobilePhone iphone=mobilePhoneFactory.getMobilePhone("Iphone");
iphone.create();
MobilePhone huawei=mobilePhoneFactory.getMobilePhone("HuaWei");
huawei.create();
MobilePhone mi=mobilePhoneFactory.getMobilePhone("Mi");
mi.create();
}
}
看一下打印: