在工厂模式中,我们没有创建逻辑暴露给客户端创建对象,并使用一个通用的接口引用新创建的对象。
1.创建shape接口
public interface shape { void draw(); }
2.创建多个shape实现类(这里创建了3个)
public class rectangle implements shape { @override public void draw() { system.out.println("inside rectangle::draw() method."); } } public class square implements shape { @override public void draw() { system.out.println("inside square::draw() method."); } } public class circle implements shape { @override public void draw() { system.out.println("inside circle::draw() method."); } }
3.创建工厂
public class shapefactory { //use getshape method to get object of type shape public shape getshape(string shapetype){ if(shapetype == null){ return null; } if(shapetype.equalsignorecase("circle")){ return new circle(); } else if(shapetype.equalsignorecase("rectangle")){ return new rectangle(); } else if(shapetype.equalsignorecase("square")){ return new square(); } return null; } }
4.使用工厂通过传递类型等信息来获取具体类的对象
public class factorypatterndemo { public static void main(string[] args) { shapefactory shapefactory = new shapefactory(); //get an object of circle and call its draw method. shape shape1 = shapefactory.getshape("circle"); //call draw method of circle shape1.draw(); //get an object of rectangle and call its draw method. shape shape2 = shapefactory.getshape("rectangle"); //call draw method of rectangle shape2.draw(); //get an object of square and call its draw method. shape shape3 = shapefactory.getshape("square"); //call draw method of circle shape3.draw(); } }
5.输出结果如下:
inside circle::draw() method. inside rectangle::draw() method. inside square::draw() method.
如对本文有疑问, 点击进行留言回复!!
网友评论