您的位置:首页 > 编程语言 > Java开发

JAVA设计模式--工厂模式

2017-06-30 14:06 218 查看
工厂模式。

代码中的工厂和现实的工厂的差别:

这里的工厂是很死板的,不像现实的工厂,有什么问题沟通都能解决。代码的工厂在不其本身的情况下,他仅仅生产内部有的“产品”,其他产品不是他不想生产,是他没有生产线,不能生产。

这里呢, 我把工厂模式分为:

1.接口工厂模式

2.抽象类工厂模式

1.接口工厂模式

顾名思义,接口工厂模式指的是用接口、实现类的方式生成的工厂模式

比如:

/**
* 人类工厂接口
* @Author lichenyi
* @Date
*/
public interface Human {
String say();
}
/**
* 女人实现类
*
* @author lichenyi
* @param:
* @return
* @date 2017/6/30 003011:31
*/
public class Women implements Human {
@Override
public String say() {
return "女人";
}
}
/**
* 男人实现类
* @param:
* @return
* @author lichenyi
* @date 2017/6/30 003011:33
*/
public class Man implements Human {
@Override
public String say() {
return "男人";
}
}
/**
* 接口工厂测试类
* @param:
* @return
* @author lichenyi
* @date 2017/6/30 003011:34
*/
public class Test1 {

public static void main(String args[]) {
//TODO
Human man = new Man();
Human women = new Women();
System.out.println(man.say());
System.out.println(women.say());
}

}


2.抽象工厂模式

也就是由抽象类的方式实现的工厂模式

/**
* 抽象工厂模式
* @author lichenyi
* @date 2017/6/30 0030 11:41
*/
public abstract class Animal {
public abstract void say();
}
/**
* 猴子继承类
* @author lichenyi
* @date 2017/6/30 0030 11:43
*/
public class Monkey extends Animal{
@Override
public void say() {
System.out.println  ("猴子");
}
}
/**
* 蛇继承类
* @author lichenyi
* @date 2017/6/30 0030 11:44
*/
public class Snake extends Animal {
@Override
public void say() {
System.out.println("蛇");
}
}
/**
* 继承工厂测试类
* @author lichenyi
* @date 2017/6/30 0030 11:44
*/
public class Test2 {
public static void main(String args[]) {
Animal monkey = new Monkey();
monkey.say();
Animal snake = new Snake();
snake.say();
}
}


有人看了,肯定会说,不是还有工厂方法模式吗?

如果你了解了工厂方法模式,你会发现,它是由接口工厂模式和抽象工厂模式组合而成的。

文中代码地址:https://github.com/lichenyigit/designModel1-simpleFactory

各位大牛,有什么疑问我们可以留言或者发我邮箱lichenyi163@163.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息