public class Main {
public static void main(String[] args) {
Implementor implementor1 = new LinuxImp();
Implementor implementor2 = new WinImpl();
Image image1 = new GifImage();
image1.setImpl(implementor1);
image1.parseFile("demo.gif");
image1.setImpl(implementor2);
image1.parseFile("demo.gif");
Image image2 = new GifImage();
image2.setImpl(implementor1);
image2.parseFile("demo.bmp");
image2.setImpl(implementor2);
image2.parseFile("demo.bmp");
}
}
class Matrix{
private String filename;
public String getFilename(){
return filename;
}
public void setFilename(String filename){
this.filename = filename;
}
}
abstract class Implementor{
public abstract void doPoint(Matrix m);//类的声明
}
class WinImpl extends Implementor{
@Override
public void doPoint(Matrix m) {
System.out.println("调用Windows系统的绘制函数绘制像素矩阵"+m.getFilename());
}
}
class LinuxImp extends Implementor{
@Override
public void doPoint(Matrix m) {
System.out.println("调用Linux系统的绘制函数绘制像素矩阵"+m.getFilename());
}
}
abstract class Image{
protected Implementor impl;
public void setImpl(Implementor impl){
this.impl = impl;
}
public abstract void parseFile(String fileName);
}
class GifImage extends Image{
@Override
public void parseFile(String fileName) {
Matrix m = new Matrix();
m.setFilename(fileName);
impl.doPoint(m);
}
}
class BMPImage extends Image{
@Override
public void parseFile(String fileName) {
Matrix m = new Matrix();
m.setFilename(fileName);
impl.doPoint(m);
}
}
class JPEGImage extends Image{
@Override
public void parseFile(String fileName) {
Matrix m = new Matrix();
m.setFilename(fileName);
impl.doPoint(m);
}
}
桥接模式:抽象和实现分离。抽象:Product,实现:Payment