首页 > 代码库 > 工厂方法模式
工厂方法模式
简单工厂模式违背了"开放-封闭"原则(再添加控制类时在简单工厂类中要修改),工厂方法模式在添加控制类时,再添加控制类对应的工厂,克服了简单工厂违背了"开放-封闭"原则。
Leifeng.java类
package factory; public class Leifeng { public void sweep(){ System.out.println("扫地"); } public void wash(){ System.out.println("洗衣"); } public void buyRice(){ System.out.println("买米"); } }
Undergraduate.java类
package factory; public class Undergraduate extends Leifeng { }
Volunteer.java类
package factory; public class Volunteer extends Leifeng { }
IFacory.java类
package factory; public abstract class IFacory { public abstract Leifeng createLeifeng(); }
UndergraduateFactory.java类
package factory; public class UndergraduateFactory extends IFacory { @Override public Leifeng createLeifeng() { Leifeng lf = new Leifeng(); return lf; } }
VolunteerFactory.java类
package factory; public class VolunteerFactory extends IFacory { @Override public Leifeng createLeifeng() { Leifeng lf = new Volunteer(); return lf; } }
Business.java类
package factory; public class Business { public static void main(String[] args) { IFacory factory = new UndergraduateFactory(); Leifeng lf1 = factory.createLeifeng(); Leifeng lf2 = factory.createLeifeng(); Leifeng lf3 = factory.createLeifeng(); lf1.buyRice(); lf2.sweep(); lf3.wash(); IFacory vfactory = new VolunteerFactory(); Leifeng vl1 = vfactory.createLeifeng(); Leifeng vl2 = vfactory.createLeifeng(); Leifeng vl3 = vfactory.createLeifeng(); vl1.buyRice(); vl2.wash(); vl3.sweep(); } }
工厂方法模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。