您好,欢迎访问一九零五行业门户网

java实现简单工厂模式

一个农场公司专门负责培育各种水果,在这个系统中的水果有葡萄,草莓和苹果,其类图如图所示。 请按以下要求编写程序:
1. 应用简单工厂方法模式,在主程序中根据键盘输入的水果名称来完成其生长状态的描述。
2  应用工厂方法模式,在主程序中根据键盘输入的水果名称来完成其生长状态的描述
//新建一个简单工厂类 simplefactory.javapublic class simplefactory{ // 此处需要定义 static 类型,在客户端 类名。方法调用 public staitc fruit getfruitobj(string type){ fruit obj = null; if(type.equals("apple")){ obj = (fruit) new apple(); }else if(type.equals("straw")){ obj= (fruit) new straw(); }else if(type.equals("grape")){ obj = (fruit) new grape(); } return obj; } }//实现水果类 fruit.javainterface fruit{ void plant(); //定义种植方法 void grow(); //定义生长方法 void harvest(); }// 实现苹果类 apple.java//此处草莓和葡萄同理,都实现接口fruit public class apple implements fruit{ @override public void plant() { // todo auto-generated method stub system.out.print("种植了苹果"); } @override public void grow() { // todo auto-generated method stub system.out.print("苹果生长了"); } @override public void harvest() { // todo auto-generated method stub system.out.print("苹果结果了"); } }//客户端接口public class main{ public staic void main(string args[]){ fruit fu =simplefactory.getfruitobj("apple"); fu.plant(); fu.grow(); fu.harvest(); } }
工厂模式实现
/实现水果类 fruit.javainterface fruit{ void plant(); //定义种植方法 void grow(); //定义生长方法 void harvest(); }// 定义一个抽象工厂方法public abstract class factory { public abstract fruit getapple(); public static factory getfruitfactory(stri ng type){ factory f = null; if(type.equals("apple")){ f=new applefactory(); f.getapple(); } return f; }//定义一个苹果的工厂public class applefactory extends factory{public apple getapple(){ //返回苹果的对象 return new apple(); }//定义一个苹果。与上面简单工厂同public class apple implements fruit{ @override public void plant() { // todo auto-generated method stub system.out.print("123"); } @override public void grow() { // todo auto-generated method stub } @override public void harvest() { // todo auto-generated method stub } }//定义主函数public class client { public static void main(string[] args) { // todo auto-generated method stub //执行 方法 fruit f =(fruit) factory.getfruitfactory("apple"); f.plant(); f.grow(); f.harvest(); }
更多java实现简单工厂模式。
其它类似信息

推荐信息