设计模式:
经验的总结,是一种设计思想
(1)创建型:创建对象
(2)结构型:对象的组成
(3)行为型:对象的功能
一、简单工厂模式:
1、优点:
客户端不需要再负责对象的创建,从而明确了各个类的指责
2、缺点:
这个静态工厂类负责所有对象的创建,如果有新的对象增加,或者某些对象的创建方式不同,就需要不断的修改工厂类,不利于后期的维护
package Demo;
class Animal{
public void bark() {
}
}
class Cat extends Animal{
public void bark() {
System.out.println("miao~");
}
}
class Dog extends Animal{
public void bark() {
System.out.println("wang!");
}
}
class AnimalFactory{
private AnimalFactory() {}
public static Animal createAnimal(String type) {
if("cat".equals(type)) {
return new Cat();
}else if("dog".equals(type)) {
return new Dog();
}else {
return null;
}
}
}
public class AnimalDemo {
public static void main(String[] args) {
Animal c = AnimalFactory.createAnimal("cat");
c.bark();
Animal d = AnimalFactory.createAnimal("dog");
d.bark();
}
}
二、工厂方法模式:
工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建由继承抽象工厂的具体类实现
1、优点:
客户端不需要再负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性
2、缺点:
需要额外的编写代码,增加了工作量
package Demo;
class Animal{
public void bark() {
}
}
class Cat extends Animal{
public void bark() {
System.out.println("miao~");
}
}
class Dog extends Animal{
public void bark() {
System.out.println("wang!");
}
}
interface Factory{
public abstract Animal createAnimal();
}
class CatFactory implements Factory{
@Override
public Animal createAnimal() {
return new Cat();
}
}
class DogFactory implements Factory{
@Override
public Animal createAnimal() {
return new Dog();
}
}
public class AnimalDemo {
public static void main(String[] args) {
Factory f = new CatFactory();
Animal a = f.createAnimal();
a.bark();
f = new DogFactory();
a = f.createAnimal();
a.bark();
}
}
三、单例模式:
保证类再内存中只有一个对象
1、如何保证类在内存中只有一个对象呢?
把构造方法私有
在成员位置自己创建一个对象
通过一个公共的方法访问
2、单例模式分为两种:
饿汉式:类一加载就创建对象
懒汉式:用的时候,才去创建对象
(1)饿汉式:
package Demo;
class Student1{
private Student1() {
}
private static Student1 s = new Student1();
public static Student1 get() {
return s;
}
}
public class StudentDemo1 {
public static void main(String[] args) {
Student1 s1 = Student1.get();
Student1 s2 = Student1.get();
System.out.println(s1.equals(s2));
}
}
(2)懒汉式:
package Demo;
class Student1{
private Student1() {
}
private static Student1 s = null;
public static Student1 get() {
if(s == null) {
s = new Student1();
}
return s;
}
}
public class StudentDemo1 {
public static void main(String[] args) {
Student1 s1 = Student1.get();
Student1 s2 = Student1.get();
System.out.println(s1.equals(s2));
}
}
开发:饿汉式(是不会出现问题的单例模式)
面试:懒汉式(可能会出现问题的单例模式)