今天第一次接触Java的工厂设计模式, 看下面:
Java代码
- interface Fruit
- {
- public
void eat();
- }
- class
Apple implements Fruit
- {
- public
void eat()
- {
- System.out.println("吃苹果"
);
- }
- }
- class
Orange implements Fruit
- {
- public
void eat()
- {
- System.out.println("吃桔子"
);
- }
- }
- class
Factory
- {
- public
static Fruit getIns(String classname){
- Fruit f;
- f = null
;
- if
("apple".equals(classname))
- {
- f = new
Apple();
- }
- if
("orange".equals(classname))
- {
- f = new
Orange();
- }
- return
f;
- }
- }
- public
class Demo6
- {
- public
static void main(String[] args)
- {
- Fruit f;
- if
(args[0]!=null){
- f=Factory.getIns(args[0
]);
- f.eat();
- }
- else
{
- System.out.println("请输入参数"
);
- }
- }
- }
程序在子类与接口之间加入了一个过渡段,通过过渡段来取得接口的实例,这个过渡段就叫做工厂。
那么是不是可以这样理解,工厂就是把主方法提供的东西加工成符合标准的产品(实例化对象)以供后面的程序处理呢?