设计模式:
设计模式(Design pattern):
是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结;
使用设计模式是为了可重用代码、让代码更容易被他人理解;
保证代码可靠性以及代码的结构更加清晰。
设计模式分类:
创建型模式(创建对象的):
单例模式、抽象工厂模式、建造者模式、工厂模式、原型模式。
行为型模式(对象的功能):
适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式。
结构型模式(对象的组成):
模版方法模式、命令模式、迭代器模式、观察者模式、中介者模式、备忘录模式、
解释器模式、状态模式、策略模式、职责链模式、访问者模式。
简单工厂模式:
又叫静态工厂方法模式,它定义一个具体的工厂类负责创建一些类的实例
优点: 静态工厂模式在不改变客户端代码的情况可以动态的增加产品。
缺点:
静态工厂类负责所有对象的创建,如果有新的对象增加,或者某些对象的创建方式不同,
就需要不断的修改工厂类,不利于后期的维护
例:
public class test {
public static void main(String[] args) {
//简单工厂模式
animal cat = AnimalFactory.getanimal("cat");
cat.eat();
animal dog = AnimalFactory.getanimal("dog");
dog.eat();
}
}
class AnimalFactory{
public static animal getanimal(String name){
if ("cat".equals(name)){
return new cat();
}else if ("dog".equals(name)){
return new dog();
}else {
return null;
}
}
}
abstract class animal{
public abstract void eat();
}
class cat extends animal{
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
class dog extends animal{
@Override
public void eat() {
System.out.println("狗啃骨头");
}
}
工厂方法模式:
工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。
优点:
客户端不需要再负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,
只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,
增强了系统的扩展性
缺点:
需要额外的编写代码,增加了工作量
例:
public class test1 {
public static void main(String[] args) {
phone xiaomi = new xiaomiFactory().createPhone();
xiaomi.watchTV();
phone huawei = new huaweiFactory().createPhone();
huawei.watchTV();
}
}
interface BigFactory{
phone createPhone();
}
abstract class phone{
public abstract void watchTV();
}
class xiaomi extends phone{
@Override
public void watchTV() {
System.out.println("看小米发布会");
}
}
class xiaomiFactory implements BigFactory{
@Override
public phone createPhone() {
return new xiaomi();
}
}
class huawei extends phone{
@Override
public void watchTV() {
System.out.println("看华为发布会");
}
}
class huaweiFactory implements BigFactory{
@Override
public phone createPhone() {
return new huawei();
}
}
单例设计模式:
内存中只允许有给类的一个实例
例:编写程序,请采用下列方式编写单例模式,并测试
饿汉式
懒汉式(线程安全版本)
package task1;
public class test {
public static void main(String[] args) {
//饿汉
student s1 = student.getStudent();
student s2 = student.getStudent();
System.out.println(s1==s2);
//懒汉
phone p1=phone.getPhone();
phone p2=phone.getPhone();
System.out.println(p1==p2);
}
}
class student {
private static student student=new student();
private student() {
}
public static student getStudent(){
return student;
}
}
class phone{
private static phone phone=null;
private phone(){
}
public static phone getPhone(){
if (phone==null){
phone=new phone();
return phone;
}
return phone;
}
}