抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。
比如超级工厂下有两个公司,一个公司为华为,一个公司为苹果。
这两个公司都生产手机和笔记本。
第一步:创建接口
/** * 电脑接口 */ public interface Computer { //上网 String internet(); } /** * 手机接口 */ public interface Phone { String call(); }
第二步:创建抽象工厂,可以生产手机和电脑
/** * 抽象工厂 */ public abstract class AbstractFactory { public abstract Phone createPhone(String brand); public abstract Computer createComputer(String brand); }
第三步:生产各类手机和电脑的实现,手机继承手机接口,电脑继承Computer接口
public class ComputerApple implements Computer{ @Override public String internet() { return "苹果电脑上网..."; } } public class ComputerHuawei implements Computer{ @Override public String internet() { return "华为笔记本上网......"; } } public class PhoneApple implements Phone { @Override public String call() { return "苹果手机打电话..."; } } public class PhoneHuaWei implements Phone { @Override public String call() { return "华为手机打电话..."; } }
第四步:创建子工厂
public class ComputerFactory extends AbstractFactory{ @Override public Phone createPhone(String brand) { return null; } @Override public Computer createComputer(String brand) { Computer computer = null; if(brand.equals("apple")){ computer= new ComputerApple(); } else if(brand.equals("huawei")){ computer=new ComputerHuawei(); } return computer; } } public class PhoneFactory extends AbstractFactory{ @Override public Phone createPhone(String brand) { Phone phone =null; if(brand.equals("apple")){ phone=new PhoneApple(); } else if(brand.equals("huawei")){ phone=new PhoneHuaWei(); } return phone; } @Override public Computer createComputer(String brand) { return null; } }
第五步:使用
public class AbstractFactoryDemo { public static void main(String[] args) { //工厂模式在JDK-Calender中的应用 Calendar calendar = Calendar.getInstance();//查看源码发现,使用的就是工厂模式 System.out.println("年:"+ calendar.get(Calendar.YEAR)); System.out.println("月:"+ (calendar.get(Calendar.MONTH)+1)); System.out.println("日:"+ calendar.get(Calendar.DAY_OF_MONTH)); //创建手机工厂 AbstractFactory phoneFactory = new PhoneFactory(); Phone phoneHuawei = phoneFactory.createPhone("huawei"); Phone phoneApple =phoneFactory.createPhone("apple"); System.out.println(phoneHuawei.call()); System.out.println(phoneApple.call()); //创建电脑工厂 AbstractFactory computerFactory = new ComputerFactory(); Computer computerHuawei =computerFactory.createComputer("huawei"); Computer computerApple=computerFactory.createComputer("apple"); System.out.println(computerHuawei.internet()); System.out.println(computerApple.internet()); } }