Loading...
Loading...
BK-CI 项目设计模式实践指南,涵盖工厂模式、策略模式、观察者模式、装饰器模式、模板方法等在项目中的实际应用。当用户学习设计模式、重构代码、设计可扩展架构或理解项目设计时使用。
npx skill4agent add tencentblueking/bk-ci design-patternsworker-common/src/main/kotlin/com/tencent/devops/worker/common/task/TaskFactory.ktobject TaskFactory {
private val taskMap = ConcurrentHashMap<String, KClass<out ITask>>()
fun init() {
// 注册内置任务
register(LinuxScriptElement.classType, LinuxScriptTask::class)
register(WindowsScriptElement.classType, WindowsScriptTask::class)
register(MarketBuildAtomElement.classType, MarketAtomTask::class)
// 通过反射扫描并注册插件任务
val reflections = Reflections("com.tencent.devops.plugin.worker.task")
val taskClasses = reflections.getSubTypesOf(ITask::class.java)
taskClasses?.forEach { taskClazz ->
val taskClassType = taskClazz.getAnnotation(TaskClassType::class.java)
taskClassType?.classTypes?.forEach { classType ->
register(classType, taskClazz.kotlin)
}
}
}
fun create(type: String): ITask {
val clazz = taskMap[type] ?: return EmptyTask(type)
return clazz.primaryConstructor?.call() ?: EmptyTask(type)
}
}// 根据 element 类型创建对应的任务实例
val task = TaskFactory.create(element.getClassType())
task.run(buildTask, param, elementId)objectpriorityConcurrentHashMapcommon-scm/src/main/kotlin/com/tencent/devops/scm/ScmFactory.ktobject ScmFactory {
private val gitApi = GitApi()
private val svnApi = SVNApi()
fun getScm(
projectName: String,
url: String,
type: ScmType, // CODE_SVN, CODE_GIT, CODE_TGIT, CODE_GITLAB, CODE_P4
// ... 其他参数
): IScm {
return when (type) {
ScmType.CODE_SVN -> CodeSvnScmImpl(...)
ScmType.CODE_GIT -> CodeGitScmImpl(...)
ScmType.CODE_TGIT -> CodeTGitScmImpl(...)
ScmType.CODE_GITLAB -> CodeGitlabScmImpl(...)
ScmType.CODE_P4 -> CodeP4ScmImpl(...)
else -> throw TaskExecuteException(
errorCode = ErrorCode.USER_RESOURCE_NOT_FOUND,
errorMsg = "Unknown repo($type)"
)
}
}
}| 工厂类 | 位置 | 用途 |
|---|---|---|
| | 创建 Worker 端 API 客户端 |
| | 创建脚本命令执行器 |
| | 创建插件运行条件处理器 |
| | 创建 Webhook 路径过滤器 |
| | 创建摘要算法实现 |
common-web/src/main/kotlin/com/tencent/devops/common/web/factory/BkApiHandleFactory.ktobject BkApiHandleFactory {
private val handleMap = ConcurrentHashMap<String, BkApiHandleInterface>()
fun registerHandle(handle: BkApiHandleInterface) {
handleMap[handle.code()] = handle
}
fun getHandle(code: String): BkApiHandleInterface? {
return handleMap[code]
}
}
// 使用示例:根据 API 类型获取对应的处理器
interface BkApiHandleInterface {
fun code(): String // 返回 API 类型标识
fun handle(request: BkApiRequest): BkApiResponse
}object// 工厂单例
object TaskFactory { ... }
object ScmFactory { ... }
object ApiFactory { ... }
// 工具类单例
object JsonUtil { ... }
object DateTimeUtil { ... }@Service // 默认单例
class PipelineService { ... }
@Component // 默认单例
class UserArchivedPipelinePermissionCheckStrategy { ... }data class PipelineTriggerEventBuilder(
var projectId: String? = null,
var pipelineId: String? = null,
var userId: String? = null,
var triggerType: String? = null,
var triggerUser: String? = null,
var eventSource: String? = null,
// ... 更多字段
) {
fun build(): PipelineTriggerEvent {
return PipelineTriggerEvent(
projectId = projectId ?: throw IllegalArgumentException("projectId is required"),
pipelineId = pipelineId ?: throw IllegalArgumentException("pipelineId is required"),
// ... 其他字段
)
}
}val event = PipelineTriggerEventBuilder()
.apply {
projectId = "demo"
pipelineId = "p-12345"
userId = "admin"
triggerType = "MANUAL"
}
.build()class Ansi(private var builder: StringBuilder) {
fun bold(): Ansi {
builder.append("\u001B[1m")
return this
}
fun fgRed(): Ansi {
builder.append("\u001B[31m")
return this
}
fun reset(): Ansi {
builder.append("\u001B[0m")
return this
}
fun toString(): String = builder.toString()
}
// 使用
val text = Ansi(StringBuilder())
.bold()
.fgRed()
.append("Error: ")
.reset()
.append("Build failed")
.toString()process/biz-process/src/main/kotlin/com/tencent/devops/process/strategy/interface IUserPipelinePermissionCheckStrategy {
fun checkUserPipelinePermission(
userId: String,
projectId: String,
pipelineId: String,
permission: AuthPermission,
message: String? = null
)
}@Component
class UserNormalPipelinePermissionCheckStrategy : IUserPipelinePermissionCheckStrategy {
override fun checkUserPipelinePermission(...) {
// 正常流水线的权限检查逻辑
}
}
@Component
class UserArchivedPipelinePermissionCheckStrategy : IUserPipelinePermissionCheckStrategy {
override fun checkUserPipelinePermission(...) {
// 归档流水线的权限检查逻辑
}
}object UserPipelinePermissionCheckStrategyFactory {
fun getStrategy(archived: Boolean): IUserPipelinePermissionCheckStrategy {
return if (archived) {
SpringContextUtil.getBean(UserArchivedPipelinePermissionCheckStrategy::class.java)
} else {
SpringContextUtil.getBean(UserNormalPipelinePermissionCheckStrategy::class.java)
}
}
}val strategy = UserPipelinePermissionCheckStrategyFactory.getStrategy(pipeline.archived)
strategy.checkUserPipelinePermission(userId, projectId, pipelineId, AuthPermission.VIEW)misc/biz-misc/src/main/kotlin/com/tencent/devops/misc/strategy/interface MigrationStrategy {
fun migrate(projectId: String, pipelineId: String): Boolean
}PipelineInfoMigrationStrategyPipelineSettingMigrationStrategyTemplatePipelineMigrationStrategyPipelineYamlInfoMigrationStrategystore/biz-store/src/main/kotlin/com/tencent/devops/store/common/handler/interface Handler<T : HandlerRequest> {
/**
* 能否满足运行条件
*/
fun canExecute(handlerRequest: T): Boolean
/**
* 核心处理逻辑
*/
fun execute(handlerRequest: T)
/**
* 执行总入口
*/
fun doExecute(handlerRequest: T, chain: HandlerChain<T>) {
if (canExecute(handlerRequest)) {
execute(handlerRequest)
}
chain.handleRequest(handlerRequest) // 传递给下一个处理器
}
}
interface HandlerChain<T : HandlerRequest> {
fun nextHandler(handlerRequest: T): Handler<T>?
fun handleRequest(handlerRequest: T) {
val handler = nextHandler(handlerRequest)
handler?.doExecute(handlerRequest, this)
}
}class StoreCreateHandlerChain(
private val handlerList: MutableList<Handler<StoreCreateRequest>>
) : HandlerChain<StoreCreateRequest> {
override fun nextHandler(handlerRequest: StoreCreateRequest): Handler<StoreCreateRequest>? {
return handlerList.removeFirstOrNull()
}
}class StoreCreateParamCheckHandler : Handler<StoreCreateRequest> {
override fun canExecute(handlerRequest: StoreCreateRequest): Boolean = true
override fun execute(handlerRequest: StoreCreateRequest) {
// 参数校验逻辑
if (handlerRequest.atomCode.isBlank()) {
throw InvalidParamException("Atom code is blank")
}
}
}
class StoreCreatePreBusHandler : Handler<StoreCreateRequest> {
override fun canExecute(handlerRequest: StoreCreateRequest): Boolean = true
override fun execute(handlerRequest: StoreCreateRequest) {
// 前置业务逻辑
}
}
class StoreCreateDataPersistHandler : Handler<StoreCreateRequest> {
override fun canExecute(handlerRequest: StoreCreateRequest): Boolean = true
override fun execute(handlerRequest: StoreCreateRequest) {
// 数据持久化
}
}val handlerList = mutableListOf(
StoreCreateParamCheckHandler(),
StoreCreatePreBusHandler(),
StoreCreateDataPersistHandler(),
StoreCreatePostBusHandler()
)
val chain = StoreCreateHandlerChain(handlerList)
chain.handleRequest(storeCreateRequest)| 处理链 | 用途 |
|---|---|
| 研发商店组件创建 |
| 研发商店组件更新 |
| 研发商店组件删除 |
| 流水线启动拦截器链 |
| Webhook 过滤器链 |
worker-common/src/main/kotlin/com/tencent/devops/worker/common/exception/TaskExecuteExceptionDecorator.ktinterface ExceptionDecorator<T : Throwable> {
fun decorate(exception: T): TaskExecuteException
}
class DefaultExceptionBase : ExceptionDecorator<Throwable> {
override fun decorate(exception: Throwable): TaskExecuteException {
return TaskExecuteException(
errorMsg = exception.message ?: "Unknown error",
errorType = ErrorType.SYSTEM,
errorCode = ErrorCode.SYSTEM_WORKER_INITIALIZATION_ERROR
)
}
}
class FileNotFoundExceptionD : ExceptionDecorator<FileNotFoundException> {
override fun decorate(exception: FileNotFoundException): TaskExecuteException {
return TaskExecuteException(
errorMsg = "File not found: ${exception.message}",
errorType = ErrorType.USER,
errorCode = ErrorCode.USER_RESOURCE_NOT_FOUND
)
}
}
class RemoteServiceExceptionD : ExceptionDecorator<RemoteServiceException> {
override fun decorate(exception: RemoteServiceException): TaskExecuteException {
return TaskExecuteException(
errorMsg = "Remote service error: ${exception.errorMessage}",
errorType = ErrorType.THIRD_PARTY,
errorCode = exception.errorCode
)
}
}object TaskExecuteExceptionDecorator {
private val factory = mapOf(
IllegalStateException::class to IllegalStateExceptionD(),
FileNotFoundException::class to FileNotFoundExceptionD(),
RemoteServiceException::class to RemoteServiceExceptionD(),
IOException::class to IOExceptionD()
)
fun decorate(exception: Throwable): TaskExecuteException {
val decorator = factory[exception::class] ?: DefaultExceptionBase()
return decorator.decorate(exception)
}
}TaskExecuteExceptionauth/biz-auth/src/main/kotlin/com/tencent/devops/auth/provider/rbac/service/DelegatingPermissionServiceDecorator.ktclass DelegatingPermissionServiceDecorator(
private val delegate: PermissionService,
private val extraCheckers: List<PermissionChecker>
) : PermissionService {
override fun checkPermission(userId: String, resourceType: String, action: String): Boolean {
// 先执行委托对象的权限检查
if (!delegate.checkPermission(userId, resourceType, action)) {
return false
}
// 再执行额外的检查器
return extraCheckers.all { it.check(userId, resourceType, action) }
}
}data class ProjectBroadCastEvent(
val projectId: String,
val eventType: EventType,
val userId: String
) : ApplicationEvent(projectId)interface ProjectEventListener : EventListener<ProjectBroadCastEvent> {
/**
* 处理项目广播事件
*/
override fun execute(event: ProjectBroadCastEvent)
}@Component
class SampleProjectEventListener : ProjectEventListener {
override fun execute(event: ProjectBroadCastEvent) {
logger.info("Received project event: ${event.eventType} for ${event.projectId}")
when (event.eventType) {
EventType.CREATE -> handleProjectCreate(event)
EventType.UPDATE -> handleProjectUpdate(event)
EventType.DELETE -> handleProjectDelete(event)
}
}
}@Service
class ProjectService(
private val applicationEventPublisher: ApplicationEventPublisher
) {
fun createProject(projectId: String, userId: String) {
// ... 创建项目逻辑
// 发布事件
applicationEventPublisher.publishEvent(
ProjectBroadCastEvent(
projectId = projectId,
eventType = EventType.CREATE,
userId = userId
)
)
}
}| 监听器 | 用途 | 位置 |
|---|---|---|
| 流水线构建质量检查 | |
| Webhook 事件处理 | |
| 定时触发构建 | |
| 构建通知 | |
| WebSocket 消息推送 | |
process/biz-process/src/main/kotlin/com/tencent/devops/process/service/pipeline/version/processor/interface PipelineVersionCreatePostProcessor {
/**
* 版本创建前的后置处理
*/
fun postProcessBeforeVersionCreate(
context: PipelineVersionCreateContext,
pipelineModel: Model,
pipelineSetting: PipelineSetting
) {
// 默认空实现
}
/**
* 版本创建后的后置处理
*/
fun postProcessAfterVersionCreate(
context: PipelineVersionCreateContext,
pipelineModel: Model,
pipelineSetting: PipelineSetting
) {
// 默认空实现
}
}@Service
class PipelineOperateLogVersionPostProcessor : PipelineVersionCreatePostProcessor {
override fun postProcessAfterVersionCreate(
context: PipelineVersionCreateContext,
pipelineModel: Model,
pipelineSetting: PipelineSetting
) {
// 记录操作日志
pipelineOperateLogService.save(
projectId = context.projectId,
pipelineId = context.pipelineId,
versionId = context.versionId,
operateType = "CREATE",
userId = context.userId
)
}
}
@Service
class PipelineEventVersionPostProcessor : PipelineVersionCreatePostProcessor {
override fun postProcessAfterVersionCreate(
context: PipelineVersionCreateContext,
pipelineModel: Model,
pipelineSetting: PipelineSetting
) {
// 发送事件
applicationEventPublisher.publishEvent(
PipelineVersionCreateEvent(
projectId = context.projectId,
pipelineId = context.pipelineId,
versionId = context.versionId
)
)
}
}@Service
class PipelineVersionCreateService(
private val postProcessors: List<PipelineVersionCreatePostProcessor>
) {
fun createVersion(context: PipelineVersionCreateContext, model: Model, setting: PipelineSetting) {
// 前置处理
postProcessors.forEach { it.postProcessBeforeVersionCreate(context, model, setting) }
// 核心逻辑:创建版本
val versionId = doCreateVersion(context, model, setting)
context.versionId = versionId
// 后置处理
postProcessors.forEach { it.postProcessAfterVersionCreate(context, model, setting) }
}
}| 后置处理器 | 用途 |
|---|---|
| 记录操作日志 |
| 发送版本事件 |
| 处理模型任务 |
| 处理权限 |
| 处理模板关系 |
| 处理子流水线 |
| 处理调试流水线 |
repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/interface IRepositoryService {
fun getRepository(projectId: String, repositoryId: String): Repository
fun listRepositories(projectId: String): List<Repository>
fun createRepository(projectId: String, request: RepositoryCreateRequest): Repository
}@Service
class CodeGitRepositoryService(
private val gitApi: GitApi,
private val credentialService: CredentialService
) : IRepositoryService {
override fun getRepository(projectId: String, repositoryId: String): Repository {
// 调用 Git API 获取仓库信息
val gitRepo = gitApi.getRepository(repositoryId)
// 转换为统一的 Repository 模型
return Repository(
projectId = projectId,
repositoryId = repositoryId,
aliasName = gitRepo.name,
url = gitRepo.url,
type = ScmType.CODE_GIT
)
}
override fun listRepositories(projectId: String): List<Repository> {
val gitRepos = gitApi.listRepositories(projectId)
return gitRepos.map { adaptToRepository(it) }
}
}
@Service
class CodeSvnRepositoryService(
private val svnApi: SVNApi,
private val credentialService: CredentialService
) : IRepositoryService {
override fun getRepository(projectId: String, repositoryId: String): Repository {
// 调用 SVN API 获取仓库信息
val svnRepo = svnApi.getRepository(repositoryId)
// 转换为统一的 Repository 模型
return Repository(
projectId = projectId,
repositoryId = repositoryId,
aliasName = svnRepo.name,
url = svnRepo.url,
type = ScmType.CODE_SVN
)
}
}@Component
class CodeRepositoryServiceLoader : BeanPostProcessor {
override fun postProcessAfterInitialization(bean: Any, beanName: String): Any {
if (bean is IRepositoryService) {
CodeRepositoryServiceRegistrar.register(bean)
}
return bean
}
}
object CodeRepositoryServiceRegistrar {
private val services = mutableMapOf<ScmType, IRepositoryService>()
fun register(service: IRepositoryService) {
services[service.getScmType()] = service
}
fun getService(scmType: ScmType): IRepositoryService {
return services[scmType] ?: throw IllegalArgumentException("Unsupported scm type: $scmType")
}
}val service = CodeRepositoryServiceRegistrar.getService(ScmType.CODE_GIT)
val repo = service.getRepository(projectId, repositoryId)process/biz-process/src/main/kotlin/com/tencent/devops/process/service/ParamFacadeService.kt@Service
class ParamFacadeService(
private val buildVariableService: BuildVariableService,
private val pipelineContextService: PipelineContextService,
private val secretService: SecretService,
private val credentialService: CredentialService
) {
/**
* 获取构建参数(门面方法)
*/
fun getBuildParameters(
projectId: String,
pipelineId: String,
buildId: String
): Map<String, String> {
// 1. 获取流水线上下文变量
val contextVars = pipelineContextService.getAllVariables(projectId, pipelineId, buildId)
// 2. 获取构建变量
val buildVars = buildVariableService.getAllVariable(projectId, pipelineId, buildId)
// 3. 获取凭证变量
val credentialVars = credentialService.getCredentialVariables(projectId, buildId)
// 4. 获取密钥变量
val secretVars = secretService.getSecretVariables(projectId, buildId)
// 5. 合并所有变量(优先级:secret > credential > build > context)
return contextVars + buildVars + credentialVars + secretVars
}
}| 排名 | 设计模式 | 使用次数(估算) | 典型应用 |
|---|---|---|---|
| 1 | 单例模式 | 50+ | 工厂类、工具类 |
| 2 | 工厂模式 | 40+ | TaskFactory, ScmFactory, ApiFactory |
| 3 | 策略模式 | 30+ | 权限检查、数据迁移 |
| 4 | 观察者模式 | 25+ | 事件监听器 |
| 5 | 责任链模式 | 10+ | Handler 链、Interceptor 链 |
| 6 | 模板方法模式 | 15+ | 后置处理器 |
| 7 | 装饰器模式 | 5+ | 异常装饰器、权限装饰器 |
| 8 | 建造者模式 | 10+ | 复杂对象构建 |
| 9 | 适配器模式 | 5+ | SCM 适配器 |
| 10 | 门面模式 | 3+ | ParamFacadeService |
TaskFactoryScmFactoryIUserPipelinePermissionCheckStrategyMigrationStrategyStoreCreateHandlerChainPipelineInterceptorChainTaskExecuteExceptionDecoratorDelegatingPermissionServiceDecorator// ❌ 避免:Java 风格的工厂
class TaskFactory {
companion object {
private var instance: TaskFactory? = null
fun getInstance(): TaskFactory {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = TaskFactory()
}
}
}
return instance!!
}
}
}
// ✅ 推荐:Kotlin object 单例
object TaskFactory {
// ...
}// ❌ 避免:手动管理单例
object PermissionService {
private val rbacService = RbacPermissionService()
private val v3Service = V3PermissionService()
}
// ✅ 推荐:Spring 依赖注入
@Service
class PermissionService(
private val rbacService: RbacPermissionService,
private val v3Service: V3PermissionService
)// ❌ 避免:复杂的 Builder
class PipelineBuilder {
private var projectId: String? = null
private var pipelineId: String? = null
fun projectId(projectId: String): PipelineBuilder {
this.projectId = projectId
return this
}
fun pipelineId(pipelineId: String): PipelineBuilder {
this.pipelineId = pipelineId
return this
}
fun build(): Pipeline { ... }
}
// ✅ 推荐:Data Class + 命名参数
data class Pipeline(
val projectId: String,
val pipelineId: String,
val name: String = "",
val desc: String = ""
)
// 使用
val pipeline = Pipeline(
projectId = "demo",
pipelineId = "p-123",
name = "My Pipeline"
)// 策略接口
interface IPermissionCheckStrategy {
fun check(userId: String, resourceId: String): Boolean
}
// 策略工厂
object PermissionCheckStrategyFactory {
private val strategies = mapOf(
"RBAC" to RbacPermissionCheckStrategy(),
"V3" to V3PermissionCheckStrategy()
)
fun getStrategy(type: String): IPermissionCheckStrategy {
return strategies[type] ?: throw IllegalArgumentException("Unknown strategy: $type")
}
}@Service
class StoreCreateService(
// Spring 自动注入所有 Handler 实现
private val handlers: List<Handler<StoreCreateRequest>>
) {
fun create(request: StoreCreateRequest) {
val chain = StoreCreateHandlerChain(handlers.toMutableList())
chain.handleRequest(request)
}
}worker-common/task/TaskFactory.ktcommon-scm/ScmFactory.ktworker-common/api/ApiFactory.ktcommon-api/factory/DigestFactory.ktprocess/biz-process/strategy/bus/misc/biz-misc/strategy/impl/log/biz-log/strategy/factory/store/biz-store/common/handler/process/biz-base/engine/interceptor/common-webhook/service/code/filter/process/biz-process/engine/listener/quality/biz-quality/listener/project/biz-project/listener/process/biz-process/service/pipeline/version/processor/process/biz-process/service/template/v2/version/processor/worker-common/exception/TaskExecuteExceptionDecorator.ktauth/biz-auth/provider/rbac/service/DelegatingPermissionServiceDecorator.ktobject