1.单例模式
临时的理解。
关于工厂模式和抽象工厂模式的差别,主要在于
工厂模式是一个工厂,而抽象工厂把工厂也做成了接口。
2.工厂方法模式
interface IProduct{
public void productMethod();
}
class Product implements IProduct{
public void productMethod(){
System.out.println("产品");
}
}
interface IFactory{
public IProduct createProduct();
}
class Factory implements IFactory{
public IProduct createProduct(){
return new Product();
}
}
public class FactoryTest {
public static void main(String[] args){
IFactory factory = new Factory();
IProduct prodect = factory.createProduct();
prodect.productMethod();
}
}
3.抽象工厂模式
interface Iproduct1{
public void show();
}
interface Iproduct2{
public void show();
}
class product1 implements Iproduct1{
@Override
public void show() {
System.out.println("product 1");
}
}
class product2 implements Iproduct2{
@Override
public void show() {
System.out.println("product 2");
}
}
interface AIFactory{
public Iproduct1 createProduct1();
public Iproduct2 createProduct2();
}
class AFactory implements AIFactory{
public Iproduct1 createProduct1(){
return new product1();
}
@Override
public Iproduct2 createProduct2() {
return new product2();
}
}
public class AbstractFactoryTest {
public static void main(String[] args){
AIFactory factory =new AFactory();
factory.createProduct1().show();
factory.createProduct2().show();
}
}
4.建造者模式
就是把赋值等操作专门提出来,其实可以理解是本来应该
写在constructor 中的代码被提了出来
class BProduct{
private String name ;
private String type;
public void showProduct(){
System.out.println("name:"+name);
System.out.println("type:"+type);
}
public void setName(String name){
this.name =name;
}
public void setType(String type){
this.type=type;
}
}
abstract class Bui{
public abstract void setPart(String name,String type);
public abstract BProduct getProduct();
}
class ConcreteBuilder extends Bui{
private BProduct product =new BProduct();
@Override
public void setPart(String name, String type) {
product.setName(name);
product.setType(type);
}
@Override
public BProduct getProduct() {
return product;
}
}
class Director{
private Bui builder = new ConcreteBuilder();
public BProduct getAProduct(){
builder.setPart("car","x7");
return builder.getProduct();
}
public BProduct getBProduct(){
builder.setPart("carB","Q5");
return builder.getProduct();
}
}
public class Builder {
public static void main(String[] args){
Director director = new Director();
BProduct product1 = director.getAProduct();
BProduct product2 = director.getBProduct();
product1.showProduct();
product2.showProduct();
}
}
5.原型模式
(方便clone)
implements cloneable{
}
创建型模式:
主要是封装了实例化函数。