线程-设计模式
设计模式:
创建型模式
简单工厂模式
工厂方法模式
单例模式
行为型模式
结构型模式
简单工厂模式
点击查看代码
public abstract class Animal {
public abstract void eat();
public abstract void sleep();
}
public class Cat extends Animal{
@Override
public void eat() {
System.out.println("猫吃鱼");
}
@Override
public void sleep() {
System.out.println("猫蜷着睡");
}
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃肉");
}
@Override
public void sleep() {
System.out.println("狗侧着睡");
}
}
public class AnimalFactory {
private AnimalFactory() {
}
public static Animal createAnimal(String name){
if("dog".equals(name)){
return new Dog();
}else if("cat".equals(name)){
return new Cat();
}else {
System.out.println("没有该动物");
return null;
}
}
}
public class FactoryDemo1 {
public static void main(String[] args) {
//养一只狗
Animal d1 = AnimalFactory.createAnimal("dog");
//养一只猫
Animal c1 = AnimalFactory.createAnimal("cat");
d1.eat();
d1.sleep();
}
}
工厂方法模式
点击查看代码
public abstract class Animal {
public abstract void eat();
public abstract void sleep();
}
public class Cat extends Animal{
@Override
public void eat() {
System.out.println("猫吃鱼");
}
@Override
public void sleep() {
System.out.println("猫蜷着睡");
}
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃肉");
}
@Override
public void sleep() {
System.out.println("狗侧着睡");
}
}
public abstract class AnimalFactory {
public abstract Animal createAnimal();
}
public class CatFactory extends AnimalFactory{
@Override
public Animal createAnimal() {
return new Cat();
}
}
public class DogFactory extends AnimalFactory{
@Override
public Animal createAnimal() {
return new Dog();
}
}
public class FactoryDemo1 {
public static void main(String[] args) {
DogFactory dogFactory = new DogFactory();
CatFactory catFactory = new CatFactory();
// //养一只狗
// Animal d1 = AnimalFactory.createAnimal("dog");
Animal d1 = dogFactory.createAnimal();
Animal d2 = dogFactory.createAnimal();
// //养一只猫
// Animal c1 = AnimalFactory.createAnimal("cat");
Animal c1 = catFactory.createAnimal();
Animal c2 = catFactory.createAnimal();
}
}
单例模式:在整个java程序运行期间,内存中某一个对象有且仅只能有一个。笔试
1. 饿汉式 工作开发中
2. 懒汉式 面试的时候说,可能会涉及线程安全的问题。
饿汉式 不调用也有对象
点击查看代码
public class Student1 {
private static Student1 student1 = new Student1();
private Student1(){}
public static Student1 getStudent1(){
return student1;
}
}
懒汉式 不调用student就一直是null只要调用了就返回student
点击查看代码
public class Student2 {
private static Student2 student2;
private Student2(){}
public synchronized static Student2 getStudent2(){
if(student2==null){
// t1 , t2, t3
student2 = new Student2();
}
return student2;
}
}

浙公网安备 33010602011771号