در این جلسه تیم کدگیت را با آموزش Bridge پترن در جاوا همراهی کنید. پیش نیاز این آموزش شامل موارد زیر است:
- آشنایی با شی گرایی در جاوا
- آشنایی با interface در جاوا
- آشنایی با متد در جاوا
- ارث بری در جاوا
- Constructor در جاوا
- This در جاوا
- دیزاین پترن
Structural Patterns
یکی از زیر شاخههای دیزاین پترن Structural Patterns است. Structural Patterns در مورد اشیا و کلاسها و چگونگی ترکیب آنها با یکدیگر صحبت میکند. برای مشخص کردن ارتباط اشیا و کلاسها با یکدیگر، این پترن ساختار سادهای را ایجاد میکند (البته بیشتر تمرکز این پترن بر روی شی گرایی است).
Bridge پترن در جاوا
وقتی که نیاز داریم یک جداسازی بین انتزاع (Abstraction) و پیاده سازی (Implementation) آن انجام دهیم از Bridge پترن در جاوا استفاده میکنیم. علت نامگذاری این پترن این است که از یک interface به عنوان پل (Bridge) استفاده میشود که باعث جداسازی بین انتزاع و پیاده سازی آن میشود.

مثال Bridge پترن در جاوا
یک Interface به نام DrawApi داریم که به عنوان یک پل عمل میکند و دو کلاس GreenCircle و RedCircle آن را Implements میکنند. کد کلاسهای گفته شده به صورت زیر است:
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: " + radius
+ ", x: " + x + ", " + y + "]");
}
}
public class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: " + radius
+ ", x: " + x + ", " + y + "]");
}
}
یک Abstract کلاس Shape داریم که از DrawAPI استفاده میکند و یک کلاس Circle که از Shape ارث بری میکند. کد کلاس Shape و Circle به صورت زیر است:
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
public class Circle extends Shape {
private int x, y, radius;
protected Circle(int x, int y, int radius,DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
تست Bridge پترن در جاوا
برای تست کدهای بالا،کد Main زیر را بزنید:
public static void main(String[] args) {
Shape redCircle = new Circle(100, 100, 10, new RedCircle());
Shape greenCircle = new Circle(100, 100, 10, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}